V
V
Vyacheslav2018-09-26 18:53:51
Laravel
Vyacheslav, 2018-09-26 18:53:51

How to exclude prefix in middleware in Laravel?

Route::group(['prefix' => '{locale}', 'where'=>['locale'=>'(kz|ru)'] , 'namespace' => 'Frontend', 'as' => 'frontend.', 'middleware' => 'locale'], function(){
    Route::group(['prefix' => 'organizations', 'as' => 'organizations.'], function(){
        Route::get('{organization}', '[email protected]')->name('show');
    });
});

<?php

//App\Http\Middleware\Locale.php

namespace App\Http\Middleware;

class Locale
{
    public function handle($request, \Closure $next)
    {
        if ($request->method() === 'GET') {
            $segment = $request->segment(1);

            if (in_array($segment, config('app.locales'))) {
                session(['locale' => $segment]);
                app()->setLocale($segment);
            }
        }

        return $next($request);
    }
}

<?php

namespace App\Http\Controllers\Frontend;

use App\Models\Base\Organization;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class OrganizationsController extends Controller
{
    public function show(Organization $organization)
    {
        return view('frontend.organizations.show', compact('organization'));
    }
}

As a result, when you open it, you /ru/orgainisation/1get this message:
Argument 1 passed to App\Http\Controllers\Frontend\OrganizationsController::show() must be an instance of App\Models\Base\Organization, string given

As I understand it, instead of one organization (id) parameter, locale is also passed to the show method.
How can prefix be excluded?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Danny Chase, 2018-09-27
@Dase23

move the route outside the function)

Route::group(['prefix' => '{locale}', 'where'=>['locale'=>'(kz|ru)'] , 'namespace' => 'Frontend', 'as' => 'frontend.', 'middleware' => 'locale'], function(){
....
});
Route::group(['prefix' => 'organizations', 'as' => 'organizations.'], function(){
        Route::get('{organization}', '[email protected]')->name('show');
});

locale is no longer passed)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question