Jonathan Tyar Jonathan Tyar - 1 month ago 25
PHP Question

$request->session didn't work in laravel 5.3 resource controller

Okay first of all, i already check that in other controller (not in resource controller) my session work very well, but when i did it in the resource controller my code for get session didnt work

Here's my resource controller

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

//tambahan
use DB;
use Session;

//model
use App\_admins;
use App\Mahasiswas;

class MahasiswaController extends Controller
{
protected $data;
protected $token;

public function __contruct(){
$this->data = array();
$this->middleware(function ($request, $next) {
$this->token = $request->session()->get('_admin_id');
if (!$request->session()->has('_admin_id')) {
abort(404);
}
return $next($request);
});
}

private function user($token){
$this->data['query'] = _admins::find($token);
}

public function index(){
echo $this->token;
}


There is more public function, but it's still empty so i not show it here to make u more confused.
And its my route in web.php

Route::group(['namespace' => 'Admin'],function(){

Route::resource('/admin/mahasiswa','MahasiswaController');
Route::resource('/admin/nilai','NilaiController');

});


Please my deadline it's getting closer, and sorry for bad english

Answer

In 5.3 the middleware hasn't run yet in the constructor, so you're unable to gather session data. But using your closure-based approach, you should be able to access it with something like this:

$this->middleware(function($request, $next) {
    // Get the session value (uses global helper)
    $this->token = session('_admin_id');

    // If the value is null, abort the request
    if (null === $this->token) abort(404);

    return $next($request);
});
Comments