Passing specified parameters in route file to the

2019-07-31 05:28发布

In laravel routes file I have written this :

Route::get('/{lang}/{page}', 'PagesController@get' )->where('lang' , $langPattern );

and in pages controller I wrote this :

public function get($lang,$page)
{
     // do something
}

But I want only to use page parameter

I created a middleware to select language and there is no need for $lang in controllers

How can I remove it ?

Can I write like this :

public function get($page)
{
     // do something
}

My language middleware :

public function handle($request, Closure $next )
{
    // URL language
    $urllang = $request->segment(1);

    if ($request->session()->has("lang")){
        $sessionLang = $request->session()->get('lang');


        // if requested url hasn't language
        if ($urllang == NULL) {
            $urllang = $sessionLang;
            return redirect('/' . $sessionLang);
        }

        // if user change the language 
        elseif ($urllang != NULL && $urllang != $sessionLang) {
            $request->session()->put('lang' , $urllang);
        }
    }
    else{
        // if there is no session lang and no url lang
        // get app main lang from config file
        // Put session and redirect
        if ($urllang == NULL) {
            $request->session()->put('lang' , config('app.locale'));
            return redirect('/' . config('app.locale'));
        }
        // if there is no session 
        // Only put session
        else{
            $request->session()->put('lang' , $urllang);
        }
    }


    // get requested language id from database
    $lang = Lang::select("id" , "short" , "name" , "title" , "keywords" , "description" , "copyrights" , "site_name")->where( ['short' => $urllang , 'active' => 1 ])->first();
    // if requested language is not exist
    if (!$lang) {
        $request->session()->put('lang' , config('app.locale'));
        abort(404);
    }else{
        Lang::set($lang);
        return $next($request);
    }

}

Thanks .

2条回答
forever°为你锁心
2楼-- · 2019-07-31 05:34

You can opt out of using arguments as parameters and get only the necessary ones from the request:

public function get(Request $request)
{
    $lang = $request->route('lang');
    $page = $request->route('page');
    // ...
}
查看更多
走好不送
3楼-- · 2019-07-31 05:46

Finally i found the best solution Just i added to my language middleware this line

$request->route()->forgetParameter('lang');

I asked it to remove lang parameter from request variable .

Hope to help you .

查看更多
登录 后发表回答