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'));
}
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))
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With