4

Each company on my app can store its own events.

A company and its events are related though the following hasMany relationship:

/**
 * The events that belong to the company.
 */
public function events()
{
    return $this->hasMany('App\Event');
}

To list a company's events, I use:

Auth::user()->company->events

Since each event stores, a lot of data that I don't need when I query the hasMany, I would like to customize the relationship to only select the id and name columns instead of the whole row.

My hasMany relationship query would be something like

DB::table('events')->where('company_id', Auth::id())->select('id', 'name')->get();

How do I take the collection returned from this result and use it as the query for my hasMany relationship, which will then correctly return a collection of event instances?

2
  • Show us your events method code from the company Model please I would suggest adding the ->select('id', 'name') part inside the relationship method. Commented Apr 18, 2019 at 11:43
  • @ZakariaAcharki I have edited my question to include the events method's code. Commented Apr 18, 2019 at 11:48

2 Answers 2

1

Add the filter inside your events method like :

public function events()
{
    return $this->hasMany('App\Event')->select('id', 'company_id', 'name');
}

Then call it like:

Auth::user()->company->events

Important update: 'company_id' is necessary for company->events link, otherwise 'events' relationship always returns empty array

Sign up to request clarification or add additional context in comments.

Comments

0

How about Auth::user()->company()->with('events:id,name')->get(); https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

Go to Eager Loading Specific Columns

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.