Romentigo
5 months ago
341
2
Laravel

Get value by foreign key

Posted 5 months ago by Romentigo

Hello, everyone! Need help to get some data from 2 models: Role and User. I've set up relationship One to Many (One Role has Many Users). Here are my migrations:

create_roles_table

Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->timestamps();
        });

create_users_table

Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('email')->unique();
            $table->bigInteger('role_id');
            $table->foreign('role_id')
                ->references('id')
                ->on('roles')
                ->onDelete('cascade');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

As you can see, users table is like default, but has one additional field role_id (foreign key). I've set relations and configured them the next way:

Role

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
     protected $fillable = ['name'];

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

    public function invites()
    {
        return $this->hasMany('Invite');
    }
}

User

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */

    protected $fillable = [
        'name', 'email', 'role_id', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function role()
    {
        return $this->belongsTo('Role');
    }
}

As you could notice, class User extends Authenticatable. So, I'm trying to get role name of a current user that logged in. I can get his all data and different fields, but don't know how to get exactly role name, not it's id. My controller:

ProfileController

public function role()
    {
        $profile = User::all()->where('id', Auth::id());
        $role = $profile->role()->name;
        return response()->json($role);
    }

I've tried something like that, I get id of current user, find him in users table and then try to get data by foreign key, but my IDE says, that role() method isn't found in User and I can't get any data by foreign key.

Please sign in or create an account to participate in this conversation.