Route Model binding in Laravel

157 Views Asked by At

I have a Laravel app and a model Category. It has a relation to itself called parent

Category.php

public function parent(): BelongsTo
{
    return $this->belongsTo(self::class, 'parent_uuid', 'uuid');
}

I'm trying to make this kind of URL,

ex.: domain.com/mobile-phones/smartphones ('mobile-phones' - category's parent, 'smartphones' - category itself)

In the routes file it should be:

Route::get('/{parent}/{category}', ...)->name('category');

Is there a way to code so i use just one Route Parameter? For example:

Route::get('/{category:parent}/{category}', ...)->name('category');

Also a way so that in blade files when i generate the url to use just the category.

route('category', ['parent' => $category->parent, 'category' => $category]); // No
route('category', $category); // Yes

I have tried making the route binding as follows:

/{category:parent}/{category}

But it gives the error that the parameter category can be used just once.

1

There are 1 best solutions below

1
mexslacker On

I would define the route like this

Route::get('/categories/{parent}/{category}')->name('category');

Because it is easy to read

and on blade run a loop on the devices and just prepare the anchor tag for the route.

@foreach ($smartPhone as $phones)
    <a href="/categories/{{ $smartPhone->parent->name }}/{{ $smartPhone->categories }}">
      Categories
    </a>
@endforeach

or if wanna display the category names

@foreach ($smartPhone as $phones)
    <a href="/categories/{{ $smartPhone->parent->name }}/{{ $smartPhone->categories }}">
      {{ $smartPhone->category }}
    </a>
@endforeach