4

I have read almost everything in web and documentation but i can't find solution for my Problem.

I have a variable stored in Session , then I want to put this variable in every url generated by route('some-route') .

In Session I have sub = "mysubid"

When I generate Route route('my-route') I want to pass this sub parameter in query string: http://domain.dom/my-route-parameter?sub=mysubid

Can you help me to solve This problem? Any helpful answer will be appreciated;

Malkhazi Dartsmelidze
  • 4,783
  • 4
  • 16
  • 40

2 Answers2

6

You can use the Default Values feature.

First create a new middleware php artisan make:middleware SetSubIdFromSession. Then do the following:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetSubIdFromSession
{
    public function handle($request, Closure $next)
    {
        URL::defaults(['sub' => \Session::get('sub')]);

        return $next($request);
    } 
}

At the end register your new middleware in app/Http/Kernel.php by adding it to $routeMiddleware.

protected $routeMiddleware = [
   // other Middlewares
   'sessionDefaultValue' => App\Http\Middleware\SetSubIdFromSession::class,
];

Add {sub} and the middleware to your route definition:

Route::get('/{sub}/path', function () {  
   //
})
->name('my-route')
->middleware('sessionDefaultValue');

Since you want this on every web route you can also add the middleware to the web middleware group:

protected $middlewareGroups = [
    'web' => [
        // other Middlewares
        'sessionDefaultValue',
    ],

    'api' => [
        //
    ] 
];
common sense
  • 3,775
  • 6
  • 22
  • 31
-2

Try this , You need to create middleware php artisan make:middleware SetSubSession

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetSubsSession
{
public function handle($request, Closure $next)
{
    if(session('sub')){
        $url = url()->full();
        return redirect($url.'?sub='.session('sub'));
    }
    return $next($request);
} 
} 

in app/http/Kernel.php

 protected $routeMiddleware = [
 ........
 'setsubsession' => \App\Http\Middleware\SetSubsSession::class,
 ]

in route.php add

 Route::group(['middleware' => 'setsubsession'], function(){ 
      //and define all the route you want to add sub parameter
 });

using this you don't need to change all your routes.This will automatic add "sub" in the route define in that middleware.

  • Please consider the performance consequences of this approach. First, this will likely result in an infinite loop, it does not check if `sub` is already set in the request, so it will attempt to redirect again. Then, if you solve that issue, every link will still end up with 2 requests: the initial request without `sub`, then the redirected request. – Adrian Gonzales Apr 27 '21 at 16:14