3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravelでapi通信時、Auth::guard('admin')->user()->idでとれない

Last updated at Posted at 2019-04-04

##症状
laravel5.8でmulti authでadmin用の認証をつくった。
けど、adminユーザーでapi通信したら、laravel側でAuth::guard('admin')->user()->idで取得しようとしてもidがとれない。

##解決法

StartSession.phpを追加

App/Http/Middleware/StartSession.php
<?php

namespace App\Http\Middleware;

use \Illuminate\Session\Middleware\StartSession as BaseStartSession;
use \Illuminate\Http\Request;
use Closure;

class StartSession extends BaseStartSession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->url() == "api/*"){
            return $next($request);
        }

        return parent::handle($request, $next);
    }
}

SessionServiceProvider.phpを追加

App/Providers/SessionServiceProvider.php
<?php

namespace App\Providers;

use Illuminate\Session\SessionServiceProvider as BaseSessionServiceProvider;
use App\Http\Middleware\StartSession;
class SessionServiceProvider extends BaseSessionServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerSessionManager();

        $this->registerSessionDriver();

        $this->app->singleton(StartSession::class);
    }
}

Kernel.phpを編集

App/Http/Kernel.php
protected $middleware = [
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\ForceHttpProtocol::class,
        \App\Http\Middleware\StartSession::class, //これを追加
    ];

##参考
https://github.com/laravel/framework/issues/17187

3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?