Auth :: check()不工作Laravel 5.5

时间:2018-03-27 16:00:48

标签: laravel-5.5

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

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

});

1 个答案:

答案 0 :(得分:0)

使用身份验证; 或使用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;
}