getRouteByKeyName another model laravel

Published 6 months ago by Dronax

I have two models:

  • Categories
  • CategoriesTranslations

In model categories I writed:

    public function getRouteKeyName(){
        return 'alias';

Column alias in model CategoriesTranslations. I need relationship?

Column alias belogns model CategoriesTranslations. How I can return alias from model CategoriesTranslations? My code is not working.



You can't reference a field from another model, hovever you can create a route model binding in your RouteServiceProvider like this:

Route::bind('category', function ($value) {
    return optional(CategoriesTranslations::where('alias', $value)->first())->category;

Ensure you set up relationships correctly.

Now you can bind in your controller like this:

public function show(Categories $category)

P.S.: Try naming your models singular. It's little bit confusing with plural names :)

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