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

让人想犯罪 __ 提交于 2019-12-11 08:18:04

问题


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 didn't 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 am not showing it here to avoid confusion. And here is my route in web.php:

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

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

});

回答1:


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);
});


来源:https://stackoverflow.com/questions/40363009/request-session-didnt-work-in-laravel-5-3-resource-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!