Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable has data in laravel blade

I wanted to check if variable is there or not in blade ..for that i have used following lines:

@if(is_null($products))
    <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
    </div>                                      
@else

    @foreach($products as $product)
        //
    @endforeach
@endif

The problem is when there is $products on blade I could show inside of foreach loop but when i get empty variable.I couldn't show the message No Data Found instead it shows only empty space? is there any problem of checking variable inside of blade?

Controller code :

public function productSearch(Request $request)
    {
        $name = $request->name; 
        $products = Product::where('name' , 'like', '%'.$name.'%')->get();
        return view('cart.product',compact('products'));
    }
like image 571
User57 Avatar asked May 04 '17 04:05

User57


3 Answers

I generally use PHP count() :

@if(count($products) < 1)
    <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
    </div>                                      
@else
    @foreach($products as $product)
        //
    @endforeach
@endif

You may also check with PHP empty() like :

 @if(!empty($products))
like image 72
Sanchit Gupta Avatar answered Sep 20 '22 06:09

Sanchit Gupta


As you can see in the documentation :

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>No users</p>
@endforelse

This code will allow you to parse all the users and display a list of them. if the $users variables is empty, then it will display a paragraph

so for you :

@forelse ($products as $product)
    //
@empty
    <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
    </div>      
@endforelse
like image 43
Mathieu Ferre Avatar answered Sep 21 '22 06:09

Mathieu Ferre


As of Laravel 5.7, You can also do this:

@empty(!$products)
   <div class="alert alert-warning">
        <strong>Sorry!</strong> No Product Found.
   </div>
@endempty
like image 45
Shreyansh Panchal Avatar answered Sep 19 '22 06:09

Shreyansh Panchal