Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

laravel @if or @isset show nothing or gives an exeption

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading