简体   繁体   中英

Laravel 8 how to name a group

This question has been asked but it's outdated in most answers I saw.

This is what I'm trying:

Route::prefix('cart')->group(function() {
  Route::get('/mycart','App\Http\Controllers\frontend\CartController@mycart')->name('mycart');
  Route::get('/checkout','App\Http\Controllers\frontend\CartController@checkout')->name('checkout');
})->name('cart');

I'd like to name the group and then in my blade be able to do:

@if (Route::currentRouteName() != 'individual_product')

The above gives me this error: Call to a member function name() on null

Any idea what i'm doing wrong?

One can configure everything with arrays:

use Illuminate\Support\Facades\Route;

Route::group(['prefix' => 'cart', 'name' => 'cart.'], function() {
    Route::get('/index',    ['as' => 'index',    'uses' => 'CartController@index']);
    Route::get('/checkout', ['as' => 'checkout', 'uses' => 'CartController@checkout']);
});

And 'as' => 'cart.index' might still be more readable than a named group (it may depend).


In Blade one can also useRoute :

@if (Route::has('cart')) @endif
@if (Route::has('cart.index')) @endif

Listing all defined routes is being supported:

php artisan route:list

You can use name prefixes like below:

Route::name('cart.')->prefix('cart')->group(function() {
  Route::get('/mycart','App\Http\Controllers\frontend\CartController@mycart')->name('mycart');
  Route::get('/checkout','App\Http\Controllers\frontend\CartController@checkout')->name('checkout');
});

for more: https://laravel.com/docs/8.x/routing#route-group-name-prefixes

in blade you can check

@if(request()->routeIs('cart.*')) // or ->routeIs('cart.mycart')
@endif

https://laravel.com/docs/8.x/requests#retrieving-the-request-path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM