【问题标题】:Auth::check() not working Laravel 5.5Auth::check() 不工作 Laravel 5.5
【发布时间】:2018-03-27 16:00:48
【问题描述】:

在我的模型中我有一个方法

public function newUserUpload(string $save_path){

    $this->photo_moderation_src = $save_path;

    if(Auth::check()){
        $this->user_id = Auth::id();
    }

    $this->save();

    return null;
}

授权后我尝试上传文件,但数据库中的记录是在没有 user_id 的情况下创建的。同时,我的刀片中的授权检查工作正常。

        @if (!Auth::check())
            <li><a href="/home">Auth</a></li>
        @else
            <li><a href="/logout/">Exit</a></li>
        @endif

这可能是因为我使用了 vueJs + Laravel api 路由吗?

Route::middleware('api')->group(function(){

    Route::post('/upload/', 'CompgenApiController@userUpload');

    Route::post('/reupload/', 'CompgenApiController@moderationReupload');

});

【问题讨论】:

  • 默认身份验证使用在 API 路由上不起作用的会话。
  • 有什么解决方案的想法吗?
  • 使用网络路由是最简单的解决方案。否则,您可以使用passport 进行 API 身份验证。

标签: laravel-5.5


【解决方案1】:

使用身份验证; 或使用 Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

if (\Illuminate\Support\Facades\Auth::check()) {
    // The user is logged in...
}

对于用户 ID,您可以使用 Auth::user()->id 或 users 表中的其他内容,例如: Auth::user()->hasRole, Auth::user()->registrationCompleted

public function newUpload(string $save_path){

    if(!Auth::check()){ return false }
    // if(!Auth::user()->registrationCompleted){ return false }
    // other Security measures

    $newUpload = new Pic(); // pics table in dataBase
    $newUpload->photo_moderation_src = $save_path;
    $newUpload->user_id = Auth::user()->id;
    $newUpload->save();

    return true;
}

【讨论】:

    猜你喜欢
    • 2020-04-20
    • 2020-09-05
    • 2015-09-06
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多