Sidart's avatar
Level 12

Check if a query has results

Hello, i have a search box on my website

now on the view i have this

    @if ($query === null)
    {
        <h4 style="text-transform: lowercase;">no results for: #{{ $query }}</h4>
        }
    @else 
    {
                <h4 style="text-transform: lowercase;">results for: #{{ $query }}</h4>
        }
        @endif 

Now only the else statement works no matter if the query is null or not.

How can i check if the query has results in it ?

0 likes
9 replies
edoc's avatar

Hi @Acidust

If your $query is a collection.

@if($query->isEmpty()) should do the trick

3 likes
Sidart's avatar
Level 12

@edoc tried it before u suggested, it says

call to a member function isempty() on string

Cronix's avatar

Show your actual $query that you are checking against.

edoc's avatar

Like @Cronix says if you show us your controller we can solve your problem

Sidart's avatar
Level 12

@Cronix , @edoc sorry guys for not posting it!!

here you go!

public function scopeSearch(Request $request)
   {
       $query = $request->q;
       $posts = Post::where('title','like',"%$query%")->paginate(10);
       return view('blog.search')->withQuery($query)->withPosts($posts);
   }
edoc's avatar
edoc
Best Answer
Level 24

You know what you can do is

    @if (count($posts))

It returns false if $posts is empty

@acidust

3 likes
technoigniters's avatar

@edoc getting error:

`Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 int(0)

Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 int(1)`

Snapey's avatar

@technoigniters start you own question with code.

Simple answer, the thing you are trying to count is not countable

oh, and edoc has not been here for many years. This question is 7 years old !

Sidart's avatar
Level 12

@edoc thanks a bunch for the help mate!!! it worked like a charm!!

Please or to participate in this conversation.