Home > Back-end >  Display different User Image in extended laravel blade template
Display different User Image in extended laravel blade template

Time:05-19

I am trying to display the User Picture in an included header template in a Laravel 8 project. Basically, I have different type of Users (Admin and Instructor) whom have different Middleware and pages. I would like to inherit the same header and display their Avatar Picture based on the User type. What I have done so far is: header.blade.php

          @php
          $instructor =  DB::table('instructors')->where('id', Auth::guard('instructor')->user()->id)->first();
          $admin =  DB::table('admins')->where('id', Auth::guard('admin')->user()->id)->first();

      @endphp
      <!-- User Account-->
      <li >  
        <a href="#"  data-toggle="dropdown" title="User">
            @if ($admin)
            <img src="{{ (!empty($admin->image))? url('upload/admin_images/'.$admin->image) : url('upload/no_image.jpg') }}" alt="">
            @elseif ($instructor)
            <img src="{{ (!empty($instructor->image))? url('upload/admin_images/'.$instructor->image) : url('upload/no_image.jpg') }}" alt="">
            @else
            <img src="{{ asset('images/1.jpg') }}" alt="">
            @endif

The error is giving me is:

Trying to get property 'id' of non-object

This error is showing ONLY when I try to login as an Instructor. The Middleware, login controller for both User type are basically the same. The Instructor login is working perfectly ONLY if I completely remove the $admin variable from header.blade.php. I tried also to put in different orders the if and elseif condition but nothing changed. Does anybody has any clue on how to solve it?

CodePudding user response:

First of all, never use @php in your Blade templates. Logic absolutely does not belong in your views, they are strictly for displaying information. If you do need access to a variable in your view, assign it in the controller and pass it to the view.

Your error is occurring because you're attempting to get information on two different guards, when a user will only ever have one or the other. Blade provides the ability to check the current user's guard with the @auth directive.

You can specify specific guards, but that is irrelevant since you have the same code inside each branch of your conditional

<!-- User Account-->
<li >  
    <a href="#"  data-toggle="dropdown" title="User">
        @auth
        <img src="{{ Auth::user()->image ? url('upload/admin_images/' . Auth::user()->image) : url('upload/no_image.jpg') }}" alt="">
        @endauth
        @guest
        <img src="{{ asset('images/1.jpg') }}" alt="">
        @endguest
    </a>
</li>

But, should you need to check for a specific guard, use this syntax:

<div>
Welcome, you are authenticated as 
@auth('admin')
an administrator
@auth('instructor')
an instructor
@endauth
</div>
  • Related