如何在控制器中获取 User()->id (Laravel 8+)

K.I*_*gor 4 authentication userid laravel

我正在尝试按user('id')选择任务,但我无法在Controller 中获取它,我从DB 中选择数据。我已经尝试了很多东西,其中一些来自stackoverflow,但它不起作用。

我试过:

1. $userId = Auth::check() ? Auth::id() : true;
2. Auth::user()->id;
3. public function getUserId(){
   
   on Model} - and then get this value on Controllers
Run Code Online (Sandbox Code Playgroud)

和其他一些事情

我有最简单的代码:

  1. 我安装了注册: npm artisan ui --auth 类似的东西
  2. 我安装了 vuejs(在 Laravel 上)
  3. 我在 Laravel 上创建了 api,在 vue 上创建了一些逻辑

我没有碰“ app.blade.php ”,它和以前一样。

我可以在文件“ app.blade.php ”中获取数据、用户名、id 和我想要的所有内容,但我需要文件夹中的这些数据->文件App\Http\Controllers{{SomeController}},但我不不知道怎么做。

有人处于这种情况吗?如何在控制器中获取用户 ID?

谢谢各位早点。

muh*_*ive 6

如果您需要用户 ID,只需使用以下其中一项:

auth()->id();
Run Code Online (Sandbox Code Playgroud)

使用 Auth 门面的

\Auth::id();
Run Code Online (Sandbox Code Playgroud)

或者,使用请求实例

$request->user()->id
Run Code Online (Sandbox Code Playgroud)

按照这个简单的控制器代码,我在这里展示了 3 种不同的方式:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SomeController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function getUserId(Request $request)
    {
        $user = Auth::user(); // Retrieve the currently authenticated user...
        $id = Auth::id(); // Retrieve the currently authenticated user's ID...

        
        $user = $request->user(); // returns an instance of the authenticated user...
        $id = $request->user()->id; // Retrieve the currently authenticated user's ID...

        
        $user = auth()->user(); // Retrieve the currently authenticated user...
        $id = auth()->id();  // Retrieve the currently authenticated user's ID...
    }
}
Run Code Online (Sandbox Code Playgroud)


Vah*_*yan 2

Auth::user()->id;
Run Code Online (Sandbox Code Playgroud)

如果您在尝试获取该控制器方法上有 Auth 中间件,这应该可以工作,请检查您是否添加了该中间件。您可以使用命令进行检查php arisan route:list