Laravel - categories as url segments, category belongs to many

I'm creating an application where user can have one speciality. User can in backend create posts assigned to his speciality, and has to associate it to one category.

I'm wondering how to manage categories when a doctor and an lawyer can use the same category, and not display all posts for all specialities where category is the same.

So actually:

  • user has one speciality

  • speciality has many categories

  • category belongs to many specialities

I think i have to create a pivot like category_speciality, as explained in Laravel doc for many to many relationships. But then i can't figure how to use speciality an category to build dedicated queries and urls.

Any help will be great !

1 answer

  • answered 2019-08-13 15:16 rits

    For URL's you could do something like:


    Route::get('/articles/{category}/{specialty}', [
        'uses' => 'PostController@index',
        'as' => 'posts.index'

    where {category} and {specialty} are a unique slug field of their title. This would result in e.g.


    public function index($categorySlug, $specialtySlug)
        $specialty = Specialty::where('slug', '=', '$specialtySlug')->first();
        $posts = Posts::where('specialty_id', '=', $specialty->id)->get();
        return view('posts.index', compact('posts'));

    That is assuming you have specialty_id in Posts table and you have correct relationships set up.

    This is just an example.