0
I’m creating an EAD application, and I need all controllers that use Middleware Students to receive from the middleware itself, the variable with the user data
I tried to define the variable in the middleware, using $request->merge(['user'] => $user);
but when I gave dd($request->user); in the controller (in __Construct), it returned null
Controller:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;
use App\Helpers\Helper;
use App\Models\Students;
class StudentController extends Controller
{
/** Currenct Student logged **/
protected $information;
public function __construct(Request $request)
{
$this->middleware(\App\Http\Middleware\Students::class);
dd( $request->user ); // <- Isso retorna null, quando na verdade deveria retornar o user
$this->information = $request->user;
}
public function index()
{
return view('dashboard.views.home', [
'user' => $this->information
]);
}
}
Middleware:
namespace App\Http\Middleware;
use Closure;
use App\Helpers\Helper;
use Illuminate\Support\Facades\Redirect;
class Students
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($user = Helper::verifyOrGet()) {
$request = $request->merge(['user' => $user]);
return $next($request);
} else {
return Redirect::to('login')->with('msg', '1');
}
}
}
The curious thing is that if I give a dd($request->user); in the middleware itself, it returns me the normal user, but in the controller no, has anyone already gone through it? Is there any solution?
Do you want to get the user logged in? Why not use the
Auth::user()
within its functions and outside the constructor ? It’s just a hint.– Ricardo Lucas
You don’t have to do any of that using
Auth::user()
if you are logged in returns the user ...– novic