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

2024-05-08

我正在尝试通过以下方式选择任务用户身份'),但我无法将其放入控制器,我从中选择数据DB。 我尝试过很多事情,其中​​一些来自堆栈溢出,但它不起作用。

I tried:

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

和其他一些事情

我有最简单的代码:

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

我没碰”应用程序.blade.php” 和以前一样。

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

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

谢谢你们之前的。


如果您需要用户 ID,只需使用以下之一:

auth()->id();

使用 Auth 门面

\Auth::id();

或者,使用 Request 实例

$request->user()->id

按照这个简单的控制器代码,我在这里展示了 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...
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在控制器中获取 User()->id (Laravel 8+) 的相关文章

随机推荐