简体   繁体   English

Auth :: id()找不到用户id并返回null,laravel

[英]Auth::id() can't find user id and return null, laravel

I am setting like and unlike options on articles. 我正在设置与文章选项不同的选项。 but in LikeController there is problem. 但在LikeController中存在问题。 when I push the like button it says -> 当我按下相似的按钮时,它说 - >

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into likes ( user_id , article_id , updated_at , created_at ) values (?, 5, 2019-05-30 07:58:34, 2019-05-30 07:58:34)) SQLSTATE [23000]:完整性约束违规:1048列'user_id'不能为空(SQL:插入到likesuser_idarticle_idupdated_atcreated_at )值(?,5,2019-05-30 07:58:34,2019) -05-30 07:58:34))

Updated JWT and Routes 更新了JWT和路线

Like model: 喜欢型号:

class Like extends Model
{
    public $timestamps = true;
    public $with = ["user"];

    protected $fillable = ["user_id", "article_id"];

    public function article()
    {
        return $this->belongsTo("App\Article");
    }

    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

and LikeController: 和LikeController:

use Auth;
use App\Article;
use App\Like;

public function like($id)
{
    $article = Article::find($id);

    $like =  Like::create([
        "user_id" => Auth::id(),
        "article_id" => $article->id
    ]);

    return Like::find($like->id);
}

public function unlike($id)
{
    $article = Article::find($id);

    Like::where("user_id", Auth::id())
        ->where("article_id", $article->id)
        ->first()
        ->delete();

    return 1;
}

I am not very sure why Auth::id() can't find the user id and return null? 我不太确定为什么Auth::id()找不到用户id并返回null?

Using JWT with vue.js 将JWT与vue.js一起使用

Routes: 路线:

Route::group(['prefix' => 'auth'], function ($router) {

  Route::post('register', 'AuthController@register');
  Route::post('login', 'AuthController@login');
  Route::post('logout', 'AuthController@logout');
  Route::post('refresh', 'AuthController@refresh');
  Route::post('me', 'AuthController@me');

});

Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

AuthController and User AuthController用户

to set controller and user model I followed the docs: https://jwt-auth.readthedocs.io/en/develop/quick-start/ 设置控制器和用户模型我遵循文档: https//jwt-auth.readthedocs.io/en/develop/quick-start/

Try importing Auth as such 尝试导入Auth

use Illuminate\\Support\\Facades\\Auth;

and getting the ID like this: 并获得这样的ID:

$user = Auth::user();
$id = $user->id;

Hope this helps 希望这可以帮助

Add this middelware on kernel.php 在kernel.php上添加这个middelware

protected $middlewareGroups = [
        'web' => [
            \Illuminate\Session\Middleware\StartSession::class,
        ],
];

this link might help : Answer Link 此链接可能有所帮助: 回答链接

Auth::user()->id

使用此代码

first: ensure that route or Controller protected by auth middleware. 第一:确保routeController受auth中间件保护。

second: ensure that you are using correct guard for auth, if using multiple guard . 第二:如果使用multiple guard ,请确保使用正确的guard进行验证。

you should specify your guard name like this: `Auth::guard('admin')->id()`

You have missed to specify the middleware => api from the route groups. 您错过了从路由组中指定middleware => api Also include the like related routes Or any protected routes within this routegroup. 还包括like相关路线或此路线组内的任何受保护路线。

config/auth.php shoud be updated as config/auth.php应该更新为

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

...

'guards' => [
    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

In routes/api.php routes/api.php

Route::post('login', 'AuthController@login')->name('login');

Route::group(['middleware' => 'api'], function ($router) {

    Route::group(['prefix' => 'auth'], function ($router) {
        Route::post('register', 'AuthController@register');
        # Route::post('login', 'AuthController@login'); // commented.
        Route::post('logout', 'AuthController@logout');
        Route::post('refresh', 'AuthController@refresh');
        Route::post('me', 'AuthController@me');

    });

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});

You seem to have not protected your LikeController routes with auth. 您似乎没有使用auth保护您的LikeController路由。

Unless you have something like this in your LikeController for constructor: 除非你的LikeController有类似的东西用于构造函数:

    public function __construct()
    {
        $this->middleware('auth:api');
    }

then you should have your LikeController routes protected like this: 那么你应该像这样保护你的LikeController路线:

Route::group([
    'middleware' => 'api',
], function ($router) {

    Route::get("/like/{id}", [
        "uses" => "LikeController@like"
    ]);
    Route::get("/unlike/{id}", [
        "uses" => "LikeController@unlike"
    ]);

});

Then the correct way of getting the logged in used is 然后使用正确的登录方式是

auth('api')->user()

or 要么

Auth::guard('api')->user()

Ok , 好 ,

so i was also having that issue with my app when i was using jwt with vue js. 所以当我使用jwt与vue js时,我的app也遇到了这个问题。 for getting current Auth::user() . 获取当前的Auth::user()

You need to pass token with your request. 您需要在请求时传递令牌。 if you check jwt core file, It getting user from token. 如果你检查jwt核心文件,它从令牌获取用户。 and you are not passing token I guess. 而且我猜你没有传递令牌。

If yes then please pass token along with your request. 如果是,那么请将令牌与您的请求一起传递。 And also check the documentation of jwt . 还要查看jwt的文档。 did you install your package properly? 你没有正确安装你的包吗? remember for laravel 5.5 or greater, that package version to use is jwt > 1.0.0 also, check the documentation of that version properly. 请记住,对于laravel 5.5或更高版本,要使用的软件包版本也是jwt > 1.0.0 ,请正确检查该版本的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM