Home > Software engineering >  laravel @if or @isset show nothing or gives an exeption
laravel @if or @isset show nothing or gives an exeption

Time:05-16

I have made in laravel v.8. a database query (eloquent) that returns several columns.

$wgName = Auth::user()
            ->join('wg_groups', 'users.wg_group_id', '=', 'wg_groups.id')
            ->get();

enter image description here

Now I want in my html view that the wg_name is displayed if it is set. I have tried the following four things:

@if(isset($wgName->wg_name))

    <h1>{{$wgName->wg_name}}</h1>

@endif

Here simply nothing is displayed

@if(isset($wgName))

    <h1>{{$wgName->wg_name}}</h1>

@endif

Exception: Property [wg_name] does not exist on this collection instance.

@isset($wgName)

    <h1>{{$wgName->wg_name}}</h1>

@endisset

Exception: Property [wg_name] does not exist on this collection instance.

@isset($wgName->wg_name)

    <h1>{{ $wgName->wg_name }}</h1>

@endisset

Here simply nothing is displayed

I have no idea why it doesn't work and I didn't find anything in the documentation. https://laravel.com/docs/8.x/eloquent

CodePudding user response:

Calling ->get() on Query builder will give you a Collection instance containing multiple users. And there is definitely no wg_name on Collection instance so the result is always false.

Try using first():

$wgName = Auth::user()
            ->join('wg_groups', 'users.wg_group_id', '=', 'wg_groups.id')
            ->first();

CodePudding user response:

Currently you are selecting all users from the database. This happens due to Eloquent redirecting non existing methods to a new query builder instance.

By changing the query to use the first() method instead of the get() method you'll receive only one record, but this would probably not be the correct record as it does not take the current user into account.

There are multiple ways to solve this issue

1: Just use a simple query to receive the wg_name.

$wgName = DB::table('wg_groups')->find(Auth::user()->wg_group_id);

2: Add a global scope to your User model to always join the wg_group data when looking up a user.

You could add the following method to your User model to always join this table when querying the users table.

protected static function booted()
{
    self::addGlobalScope('include_wg_group', function (\Illuminate\Database\Eloquent\Builder $query) {
        $query->join('wg_groups', 'users.wg_group_id', '=', 'wg_groups.id');
    });
}

Now everytime you receive an instance of a User it will have all the info of wg_groups joined into it. This allows you to just grab the name like this:

$wgName = Auth::user()->wg_name;
  • Related