Renan Coelho
Renan Coelho

Reputation: 1449

Laravel 5.4: How to set a first and default parameter to route() function

I 'm passing a prefix parameter to all routes on my webiste:

Route::prefix("{param}")->group(function () {
    # code...
});

Sometimes I need to call the route() function in the views. The problem is there, because I need to pass the $param as first parameter like:

resources\views\welcome.blade.php

<a href="{{ route('about-us', $param) }}">About Us</a>

The question is: I do not need to pass $param in route() function because its not necessary. How to avoid this and do just the following:

<a href="{{ route('about-us') }}">About Us</a>

Is there a way to create a middleware and set a "global" configuration to route() function?

Upvotes: 1

Views: 1648

Answers (3)

Renan Coelho
Renan Coelho

Reputation: 1449

By using @William Correa approach, I've created a helper function to setting up a prefix parameter to default Laravel function helper route().

app\Helpers\functions.php

function routex($route, $params = [])
{
    if (!is_array($params)) {
        $params = [$params];
    }

    // Set the first parameter to App::getLocale()
    array_unshift($params, App::getLocale());
    return route($route, $params);
}

Now when I try to get a link to route() by name, just use routex('about-us') and the routex() function will put a prefix parameter like App::getLocale() or anything else you want.

Upvotes: 1

DevK
DevK

Reputation: 9942

Yeah, like this:

Route::get('about-us', 'AboutController@getAboutUs')->name('about-us');

Now if you call route('about-us') it will generate url to .../about-us.

Upvotes: 0

Eddy05
Eddy05

Reputation: 5

In your Controller you can protect your route like this:

 public function __construct()
    {
        $this->middleware('auth');
    }

and than

Route::get('/about', 'yourcontroller@yourmethod')->name('name');

or in your web.php you can declare a group without a prefix like this

Route::namespace('name')->group(function () {
    Route::get('/about', 'yourcontroller@yourmethod')->name('name');
});

Upvotes: 0

Related Questions