Darius
Darius

Reputation: 1664

Output route url with two variables using only ID

If possible..how would this be done? Laravel 5.5

route('section.category.subcategory',$subcategory->id) 

must output (routes/web.php has the get:: set as this too)

/section/{parent_slug}/{subcategory_slug}

I could easily do

route('section.category.subcategory',[
                                     'subcategory_slug' => $subcategory->slug, 
                                     'parent_slug'=>$parent->slug
                                     ]
);

but I'm trying to avoid having to declare those things all the time.

I thought getRouteKeyName in model would be first place to go to, but it binds to only one variable as far as I could find.

RouteHandler isn't the place to do anything either because it reads the url, not outputs it right?

I'm assuming in some file that I don't know about I will have to set this sort of logic.

if(requested_route is section.category.subcategory)){
   // get the parent_id of ID provided,
   // get parent's slug
   // build the url.
}

Even better, I think I could do a left join when pulling the list of subcategories, so I have $subcategory->parent_slug instead of going for $parent->slug. This way

route('section.category.subcategory',[$subcategory]) 

has all the variables it needs to work with.

Upvotes: 0

Views: 136

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

I think for this helper would be a good choice so you could create url like this:

route('section.category.subcategory',build_category_parameters($subcategory)) 

and you can create function like this:

function build_category_parameters($subcategory)
{
   // here any logic that is needed

   // here return array something like this
   return [ 'subcategory_slug' => $subcategory->slug, 
            'parent_slug'=> $subcategory->parent->slug
          ];
}

If you don't have helper file already you can create one using this way Laravel - require php script in a service provider

Upvotes: 1

Related Questions