Home > front end >  How to add object in laravel relationships
How to add object in laravel relationships

Time:12-30

How to add extra object in laravel relationship when fatch data.

Here is my code:

$list = new self;
$list = $list->where('uuid', $uuid);
$list = $list->where('user_id', $user->id)->orWhere('to_user_id', $user->id);
$list = $list->with(['touser' => function($q1) {
    $q1 = $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified');
}]);
$list->with(['user' => function($q1) {
    $q1 = $q1->select('id', 'name', 'email', 'user_image', 'is_active', 'is_profile_completed', 'is_verified');
}]);

$list = $list->first();

I want to add extra object in response like:

"Contest": {
   "name": NULL,
   "type": 0
}

CodePudding user response:

You have multiple ways to add extra objects in response

The first option is

You have to define the eloquent relationship in the list model like this

public function contest()
{
    return $this->belongsTo(Contest::class);
}

and then you can eager load that relationship using a method like this

$list->with('contest')->first();

another option is You can set custom relationships like this

$list->setRelation('contest', collect(['name'=>null,'type':0]));
  • Related