Is there any way to define a specific title on Laravel routes?

Asked

Viewed 241 times

1

In the Laravel 5, I am creating a menu dynamically, making a foreach in the list of registered routes.

So I can have a menu displayed each time a new route is created, but I’m only listing the ones that contém the method index in the controller.

Thus:

@foreach(Route::getRoutes() as $route)
 @if(Str::finish($route->getName(), '.index'))
 <li>
   {{ link_to_route($route->getName()) }}
 </li>
 @endif
@endforeach

However, in the second parameter of link_to_route, it would be interesting to pass a title for this route. So I would have the links with the name well descriptive for the route, instead of displaying the url complete.

Is there any way in the creation of Rota, create a title for that route (I’m not talking about the option "as" which is used internally)?

Is there any way to define an attribute in the controller method or in the route for me to use as the Route? I can do that in Laravel?

1 answer

1


Yes, with a little creativity you can create "custom attributes" on Laravel. I mean by that you can create indexes on array passed to the route.

My suggestion is to do this with indexes that are not used in the Laravel internally.

For example, the attribute could be used quietly title.

So we can do it this way:

  Route::get('/', [
    'uses' => 'HomeController@getIndex', 'title' => 'Página inicial'
  ]);

  Route::get('/usuarios', [
     'uses' => 'UsersController@getIndex', 'title' => 'Página de usuários'
  ]);

 // Observe que não defini `title` aqui

 Route::post('/usuario/cadastrar', ['uses' => 'UserController@postStore']);

Then we could do it the following way in the view, to be able to list only rotas which contain title:

 @foreach(Route::getRoutes() as $route)
     @if(array_key_exists('title', $action = $route->getAction()))
         {{ link_to_route($route->getName(), $action['title']) }}
     @endif
 @endforeach

Note that only routes containing the index are displayed title. That is, the others are skipped.

I believe this is the best way to create your menus dynamically with the Laravel.

I hope this can help many :)

  • Very interesting @Wallacemaxters, I think this might simplify something I was doing in my application... how do I display this custom attribute in the view I loaded? Like, when I access the home I pull the title inside a <H1> for example

  • just put {{ $action['title'] }} ?

  • @Raylansoares notes that in if who has the array_keys_exists i create the variable $action within the if. This not to call the method $route->getAction() twice...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.