mohamad shahkhajeh
mohamad shahkhajeh

Reputation: 41

how attach the relationship when getting data from database by model in laravel

I want to attach the relationship when getting data from database by model in laravel. I use these code to do this. but I know there is better way to do this.

thanks for your helps.

$courses = Cource::orderBy('id' , 'desc')->take($count)->get();
 foreach($courses as $cource){
        $cource['image'] =  $cource->image()->get();
        $cource['rate'] = $cource->rate()->get();
}

Upvotes: 2

Views: 180

Answers (2)

mohamad shahkhajeh
mohamad shahkhajeh

Reputation: 41

$courses = Cource::orderBy('id' , 'desc')
->take($count)
->with(['image', 'rate'])
->get();

the condition is that use all relationship except morph relationship

Upvotes: 0

Alberto
Alberto

Reputation: 12929

You might want to use with:

$courses = Cource::orderBy('id' , 'desc')
    ->take($count)
    ->with(['image', 'rate'])
    ->get();

Upvotes: 1

Related Questions