代码之家  ›  专栏  ›  技术社区  ›  Michael Emerson

Laravel 5 Auth::user()除index()函数和blade模板外,其余位置均为空

  •  0
  • Michael Emerson  · 技术社区  · 7 年前

    我花了一段时间试图弄明白这一点,但我没有找到决定性的解决方案。基本上,我试图根据登录的用户检索客户端列表,但除了 index() 函数where is返回视图,以及显示登录用户名的刀片模板。

    这是我的客户端控制器。php:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Http\Models\Client;
    use App\Http\Requests\GetClientsRequest;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Log;
    
    class ClientController extends Controller
    {
        protected $user;
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
    
           $this->middleware(function ($request, $next) {
               $this->user = Auth::user();
    
               return $next($request);
           });
        }
    
        /**
         * Show the clients page.
         *
         * @return \Illuminate\Http\Response
         */
        public function index()
        {
            Log::info("client user: " . print_r($this->user, 1));
            return view('page');
        }
    
        public function getClients()
        {
            $currentUser = Auth::user();
    
            if ($currentUser) {
                $clients = Client::with('account')
                        ->where('user_id', $currentUser->account)
                        ->get();
    
                $collection = collect($clients);
    
                return response($collection->toArray());
            }
        }
    }
    

    索引函数中的Log打印出用户对象没有问题,但是在 getClients() 函数,它是空的。我也试着在 __construct() :

    $this->middleware('auth');
    

    根据我使用的Laravel模板,但是每当我调用 getClients API路由我总是收到401未经授权的错误。

    这是我的 api.php 路由文件(尽管当前仅使用getClients调用):

    <?php
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Route;
    
    /*
    |--------------------------------------------------------------------------
    | API Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register API routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | is assigned the "api" middleware group. Enjoy building your API!
    |
    */
    
    Route::middleware('auth:api')->get('/user', function (Request $request) {
        return $request->user();
    });
    
    Route::get('welcome-message', 'DashboardController@getWelcomeMessage');
    
    Route::prefix('clients')->group(function () {
        Route::get('/', 'ClientController@getClients');
        Route::get('/{clientId}', 'ClientController@getClient');
        Route::post('/', 'ClientController@postCreateClient');
        Route::put('/{clientId}', 'ClientController@putUpdateClient');
    });
    

    还有我的 web.php 路由文件:

    <?php
    
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\Route;
    
    /*
    |--------------------------------------------------------------------------
    | Web Routes
    |--------------------------------------------------------------------------
    |
    | Here is where you can register web routes for your application. These
    | routes are loaded by the RouteServiceProvider within a group which
    | contains the "web" middleware group. Now create something great!
    |
    */
    
    
    Auth::routes();
    
    Route::get('/', 'HomeController@index')->name('dashboard');
    Route::get('/clients', 'ClientController@index')->name('clients');
    

    系统知道我已登录,因为我甚至无法访问客户端仪表板,所以我不明白为什么我无法从 Auth::user() 在函数中-除非我不正确地使用中间件?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Tom    7 年前

    您必须使用 auth:api 允许的中间件 API authentication

    为此,请将此中间件添加到API路由,在这种情况下,请忽略在 __constructor

    Route::group([
        'prefix' => 'clients',
        'middleware' => ['auth:api']
    ], function(){
        Route::get('/', 'ClientController@getClients');
        // ... etc
    });
    

    确保您有一个有效的访问令牌来访问API。将API与JS前端一起使用时, read about it 在Laravel文档中。

    请注意,“web”身份验证(中间件: auth )使用不同的 机械装置 API身份验证(中间件: 认证:api )对用户进行身份验证。

    推荐文章