Home > Net >  laravel how to get use with relation in blade after login
laravel how to get use with relation in blade after login

Time:09-22

I am using Laravel 8 and the User model has relation with model UserProfile
as following

class User extends Authenticatable
{
    use LaratrustUserTrait;
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;
.
.
.
public function profile(){
        return $this->hasOne(UserProfile::class,'user_id');
    }
}

when i create a new user i directly do login for him and redirect him to dashboard as following

 Auth::login($user, true);

return $this->sendSuccessResponse();

but my question is how i can use user data with it's userProfile relation in blade or controller I tried to use the following code in blade

<img src="{{Auth::user()->profile->image}}" id="profile-img" alt="">

but i get the following error message

Attempt to read property "image" on null

CodePudding user response:

Your profile relationship is either malformed or missing.

This error means that you are trying to get the property image on a value of null.

That's because Auth::user()->profile returns null, then Auth::user()->profile->image is like writing (null)->image.

This can be caused by several things:

  • Missing data in the database
  • Wrong columns name
  • Wrong tables name

The easiest thing to bypass this error would be to only display the image when this relationship isn't null:

@if(Auth::user()->profile !== null)
    <img src="{{Auth::user()->profile->image}}" id="profile-img" alt="">
@endif

However, it would be better to understand why it's null, at least to avoid further problems in your project.

CodePudding user response:

Apply these changes in your User model. I think it will work for you.

User Model

class User extends Authenticatable
    {
        /**
         * The relationships that should always be loaded.
         *
         * @var array
         */
        protected $with = ['profile'];
    
        /**
         * Get the user profile.
         */
        public function profile()
        {
            return $this->hasOne(UserProfile::class);
        }
    }
  • Related