【问题标题】:Print user group name with Auth::User()->user_group->name in Laravel 4在 Laravel 4 中使用 Auth::User()->user_group->name 打印用户组名称
【发布时间】:2015-02-10 14:20:32
【问题描述】:

我正在尝试使用 Auth::user()->user_group->name 在视图中显示用户组名称,但显然这不起作用,因为我一直在尝试获取非对象的属性。

代码如下

User_Group.php 模型

<?php

class User_Group extends Eloquent {

    protected $table = 'user_groups';

    public function users() {
        return $this->hasMany('User');
    }

}

User.php 模型

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function user_group()
    {
        return $this->belongsTo('User_Group', 'user_groups_id');
    }

    public function getGravatarAttribute()
    {
        $hash = md5(strtolower(trim($this->attributes['email'])));
        return "http://www.gravatar.com/avatar/$hash?s=100";
    }

    public function isAdmin()
    {
        return $this->user_groups_id == 1;
    }

}

我的 profile.blade.php 视图

<small><p class="pull-right">{{ Auth::user()->user_group->name }}</p></small>

执行以下操作将打印用户组 ID 参考:

 {{ Auth::user()->user_groups_id }}

【问题讨论】:

    标签: laravel-4 model echo


    【解决方案1】:

    将方法重命名为 group 而不是 user_group

    【讨论】:

    • 成功了……但是为什么呢?不支持使用下划线吗?
    • 我真的不知道,我以前遇到过这个问题,它一定是某种命名约定的事情
    • 明白了!非常感谢!
    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 2020-10-03
    相关资源
    最近更新 更多