【问题标题】:Get username from ID从 ID 获取用户名
【发布时间】:2018-03-28 11:22:30
【问题描述】:

我在 Laravel 5.5 应用程序中有一个刀片模板,它返回一个用户 ID 整数

我正在寻找一种从刀片模板中的值获取用户名的方法

值只是保存在表中,没有建立关系,有没有不用建立关系就可以得到用户名的方法?

** 更新 **

我的产品控制器看起来像这样...

public function index()
{

    $users = User::all();

    $products= Product::all();

    return view('products.index',compact('products', 'users'));     
}

所以现在我在刀片模板中提供了用户,但现在我需要从产品中包含的 id 获取用户

【问题讨论】:

  • 为什么不把用户对象返回给视图,只输出你需要的东西?
  • 是给认证用户的吗??然后尝试 Auth::id();
  • 如果您将其返回到服务器,那么您将无法使用该 ID 进行任何操作
  • 他返回用户 $users = User::all();。我猜你在刀片上做一个foreach?我们可以看到刀片代码吗?它应该像 $user->name

标签: laravel


【解决方案1】:

在将用户数据传递给视图的控制器中,您可以传递整个 $user 对象并将其打印到您的视图中,如 {{ $user->name }} 或为自己设置一个仅包含用户名的变量并将其传递给但是你正在使用它。

我会做第一个,比如:

public function index()
{
    $user = User::where('id',$id)->firstOrFail();
    return view('dashboard.index', compact('user'));
}

或者,如果您要从数据库中获取所有用户,例如:

public function index()
{
    $users = User::all();
    return view('dashboard.index', compact('users'));
}

那么在你看来你可以这样做

@foreach($users as $user)
    {{ $user->name }}
@endforeach

编辑

自从看到您更新的问题后,您将受益于在您的 users 和您的 products 之间建立关系。所以,你会说user has many productsproduct belongs to a user

class User extends Model
{
    /**
     * Get all of the products for the user.
     */
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

然后

class Product extends Model
{
    /**
     * Get the user that is assigned to the product
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

设置完成后,您可以循环浏览您的产品并获取如下用户名:

@foreach($products as $product)
    {{ $product->user->name }}
@endforeach

【讨论】:

  • @fightstarr20 我刚刚为您添加了第二个示例
  • 我在这样的“产品”控制器中执行此操作... public function index() { $products = Product::all();返回视图('products.index',compact('products')); }
  • 目前没有,我正在尝试第一个示例,但我得到了未定义的变量 id。现在尝试解决
  • @fightstarr20 在不知道您如何使用它或如何尝试使用它的情况下,很难为您提供一个完全有效的解决方案。如果您使用一些代码示例更新您的问题以显示所需的结果,我可以稍微澄清一下。这些只是为您指明正确方向的示例
  • 你真的需要建立关系,这才是正确的做法@fightstarr20
【解决方案2】:
{{\App\User::findOrFail($id)->name}}

【讨论】:

  • 理想情况下视图不应该处理逻辑
  • 如果用户不存在,该方法将抛出带有重定向的 HTTP 异常。由于标头已经发送——它已经在渲染/输出视图——你可能会收到类似于Cannot modify header information - headers already sent的警告消息。
【解决方案3】:

创建帮助文件:按照此规则制作:https://laravel-news.com/creating-helpers

然后做一个这样的函数:

function getUsername($uerId) {
 return \DB::table('users')->where('user_id', $userId)->first()->name;
}

并像这样从您的视图中调用此函数:

 {{getUsername($id))}} //it will print user name;

【讨论】:

  • 或者,在控制器中执行逻辑并将其传递给视图,无需创建帮助程序或其他文件
  • Helper 看起来不错,但在控制器中执行逻辑听起来更好。目前我只是使用 ::all 返回,现在阅读如何自定义控制器的输出
【解决方案4】:

Auth::user()->name 如果用户在线。如果不是,您必须具有控制器功能,例如:

$users = User::all();

and in blade 

@foerach($users as $user)
{{$user->name}}
@endforeach

【讨论】:

    猜你喜欢
    • 2019-12-30
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2016-04-27
    • 1970-01-01
    • 2021-02-06
    • 2020-07-05
    相关资源
    最近更新 更多