Sunday, April 16, 2017

Retriving data by other field than id in has Many relations

I have a has many relation between models: post and category in laravel application. I've defined these relations as:

public function category(){

        return $this->belongsTo('artSite\category');

    }

 public function posts(){

        return $this->hasMany('artSite\post');
    }

Now I'm trying retrieve posts belonging to the particular category which are derived in http request:

Route::get('posts/categories/{categoryName}','postsViewController@showPostGivenCategory')

Below I show my controller function(It does works fine!):

 public function showPostGivenCategory($categoryName){



     $category = category::where('category_name','=',$categoryName)-first();
     $posts = category::find($category->id)->posts;
     return view('pages.homePage')->with('categories',$categories)with('posts',$posts);

 }   

In this solution I'm creating 2 queries. Is any possible way to create 1 quuery to retrieve posts of particular category in has many relation?

Something like that doesn't work:

$posts = category::where('category_name','=',$categoryName)->posts;

Could someone help me with this problem? I would be very grateful, greetings.



via Krzysztof Michalski

Advertisement