skip to Main Content

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
}

2

Answers


  1. 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]));
    
    Login or Signup to reply.
  2. try this:

    $list->prepend([
                'Contest' => [
                     'name' => null,
                     'type' => 0
                ]
            ]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search