boldstar
1 year ago

How to use show($id) with foreign key relationship?

Posted 1 year ago by boldstar

Hi, I am struggling to understand how I can get a model by $id and also include the belongsTo() relationship of the parent model.

Here is my relationship.

  1. Client hasMany Engagements
  2. Engagements belongsTo Client

I want my show($id) method to return a single engagement by id with the client that matches the client_id stored as a foreign key on the engagement table..

Currently I have this as my method but the ->first() always returns the same object which is not what I want...

public function show($id)
    {
        $engagement = Engagement::find($id)->with('client')->first();
        return response($engagement);
    }

here are the Eloquent Models

Client

public function engagements()
    {
        return $this->hasMany('App\Engagement');
    }

Engagement

 public function client() 
    {
        return $this->belongsTo('App\Client');
    }

Thanks in advance for any help!

Please sign in or create an account to participate in this conversation.