samedi 29 décembre 2018

How to set Eloquent withDefault on some condition rather than null and set default value from modal

I am creating an API in laravel to get all posts with their creator.

I have following tables - posts id title desc creator_id -> belongsTo users id creator_name type - ENUM('system','user') "when 'system', creator_name will be given else creator_id is used get name from users table"

users id name . .

In laravel we have Post and User Model. System posts are created by admin and a creator_name is provided. For system posts we want to show creator name from the creator_name field in posts table and not the details of admin user.

What is the best way to achieve this in laravel?

Post Model -

class Post{
    function creator(){
        return $this->belongsTo('App\Models\User', 'creator_id');
    }
}

Post Controller -

public function index()
{
    $posts = Post::with('creator')->paginate();
    $data = $posts->toArray();

    foreach ($data['data'] as $key => &$value) {
        if($value['type'] === 'system' && isset($value['creator'])){
            $value['creator']['name'] = $value['creator_name'];
            unset($value['type']);
            unset($value['creator_name']);
        }
    }

    return $this->sendResponse($data);
}




expected:
Posts -

[
    {
        "id": 1,
        "title": "some title",
        "desc": "some description",
        "creator_name": NULL,
        "creator_id": 123,
        "creator": {
            "id": 123,
            "name": "John Doe",
        },
        "type": "user"
    },
    {
        "id": 2,
        "title": "some other title",
        "desc": "some other description",
        "creator_name": "Jane Doe",
        "creator_id": 12, // admin user
        "creator": {
            "name": "Jane Doe", // creator_name rather than details of admin user
        },
        "type": "system"
    }
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire