eloquent relationship belongsTo('Spatie\Permission\Models\Role', 'id', 'id') not working

Viewed 15

so i was following this tutorial [laravel 8 crud tutorial]1

and i wanted the create,edit,delete,show to be modal. i manage to make it work on show,delete and create but my edit is not working.

user.php (model)

<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;

class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;

/**
 * The attributes that are mass assignable.
 *
 * @var array<int, string>
 */
protected $fillable = [
    'name',
    'email',
    'password',
];

/**
 * The attributes that should be hidden for serialization.
 *
 * @var array<int, string>
 */
protected $hidden = [
    'password',
    'remember_token',
];

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

public function userRole()
{
    
    return $this->belongsTo('Spatie\Permission\Models\Role', 'id', 'id');
}
}

Edit modal


                    <div class="col-xs-12 col-sm-12 col-md-12">
                        <div class="form-group">
                            <strong>{{ __('Role') }}:</strong>
                            {!! Form::select('roles[]', $roles,$user->userRole->name, array('class' => 'form-control','multiple')) !!}
                        </div>
                    </div>

if i remove the name in $user->userRole i get no error, but when i put a name in$user->userRole->name i get an error

Trying to get property 'name' of non-object (View: C:\Apache24\htdocs\BDProject_v1\resources\views\Users\modal\edit.blade.php)

1 Answers

Well, that means you are trying to get the property of a non-object. Please dump the value and check if it is an object or an array.

var_dump($user->userRole);
Related