Amartya Barua
Amartya Barua

Reputation: 155

Show link based on query result

I want to show a link if there are results from query. I get an error when the table is empty. Thanks in advance!

The html:

...
<div class="notification">
            <header><h3>Notification</h3></header>
            @if(Auth::user()->friends()->where(['status', 'received'])->first())
                <a href="" class="">You have a new request!</a>
                @endif
        </div>
...

The error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause'
 (SQL: select * from `friends` where `friends`.`user_id` = 2 and `friends`.`user_id` is not null and (`0` = status and `1` = received) limit 1) 

At the beginning the table is empty unless the user saves some information in the table. How can I solve this?

Upvotes: 0

Views: 31

Answers (2)

Khawlah Elshah
Khawlah Elshah

Reputation: 144

The issue is with the where clause in the query, you are passing an array but not using the array => operator between the index and the value, so php will think that both status and received are array values and will not use status as the index, for more details php arrays.

so to solve this you can use where clause without array, since you are checking only one index

Auth::user()->friends()->where('status', 'received')->first()

or you can use the array, but make sure to use => operator

Auth::user()->friends()->where(['status' => 'received'])->first()

Upvotes: 0

nakov
nakov

Reputation: 14268

The query is okay, except the where clause, you should not pass an array there like that, so try replacing the condition with this:

@if(Auth::user()->friends()->where('status', 'received')->first())

first returns null if not found which is false and it will work okay.

And as a suggestion I wouldn't put the query in the view, I would pass it from the controller better. So you can store into a variable for example:

$newFriends = Auth::user()->friends()->where('status', 'received')->first();

return view('your_view_name', compact('newFriends'));

Then in the view

@if($newFriends)
...
@endif

Upvotes: 1

Related Questions