#Laravel 8 Storing custom route attributes

4 messages · Page 1 of 1 (latest)

chrome shale
#

What is the most simple way to store custom attributes such as page titles or other key value pairs that may be attached to a route?

For example, say I want to add my own metadata data to:

Route::get('/themetest', [MyController::class, 'list'])->name('themetest');

I thought I could add a route macro to save metadata to be retrieved later using an addMetadata method like

Route::get('/themetest', [MyController::class, 'list'])->name('themetest')->addMetadata('title' => 'Page Title');

Is that possible? Doesn't seem like it is.

Is there a standard way to store this type of info? Or, any practical way? I thought maybe I could store them using default(), but that could change the default parameters for a controller function.

fallen torrent
#

Hello @chrome shale,

the only way I can think of to add a title for your view from your route would be to create a middleware and pass is an argument. The middleware can then share a variable with all views.

Middleware :

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;

class TitleMidleware
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next, $title)
    {
        View::share('title', $title);

        return $next($request);
    }
}

Add a shortcut in app/http/Kernel.php

protected $routeMiddleware = [
    ...
    'title' => TitleMidleware::class,
 ];

Then in your route you should be able to do this:

Route::get('/themetest', [MyController::class, 'list'])->name('themetest')->middleware('title:myCustomTitle');

I did not test but that's the idea.

#

That said, I do not recommend doing this. It is not the route's role to define the title of the view. Either hard code it directly in your view, or let the controller pass the title to your view.

chrome shale
# fallen torrent That said, I **__do not recommend__** doing this. It is not the route's role to ...

Ok thanks. My perspective: I'm more of a pragmatist than a purist. Routes and route groups can be a good approximation of pages. I would hate to have to dig through business logic in controllers to find hard coded page titles, and having to dig through templates for a text configuration setting also seems impractical and a wase of time. So, putting some properties in a route seems like a great option. This is more configuration related than UI related and routing already does more than defining routes. So I would go for being practical over sticking to previous restrictions... But, I don't know, I might be alone in that way of thinking lol.

If there's any way I could handle this like a configuration issue, not a business logic or template issue, I would be interested.