-1

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.

2
  • 1
    I would expect that Route::get('/{parent}/{category}', ...)->name('category'); would work with route('category', ['parent' => $category->parent_id, 'category' => $category->id]). Your Controller method would then be something like public function category(Category $parent, Category $category) { ... }. Commented Nov 1, 2022 at 14:54
  • 1
    No, I don't believe the routing is possible the way you want it. Route::get('/{parent}/{category}', ...)->name('category'); is the usual and accepted way to do it. Commented Nov 1, 2022 at 14:54

1 Answer 1

-1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That's a little better, but this still won't work. Your @foreach() doesn't make a lot of sense when you're then referencing it as {{ $smartPhone->parent->name }}. $smartPhone is the outer variable (a Collection, Array, etc.), and this would likely throw an error. $phone->parent->name might work, but what is $smartPhone? That is not in the original question, so you're kinda making up code here and hoping it answers the question. Please test your code locally and post an answer that actually works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.