Reputation: 711
I created a simple search in Laravel, to find stuff by search term
Controller
public function search()
{
$search = request()->query('search');
$data = array();
$data['books'] = Book::where('name', 'LIKE', "%{$search}%")->simplepaginate(12);
$data['authors'] = Author::where('name', 'LIKE', "%{$search}%")->simplepaginate(12);
return view('search', compact("data"));
}
Blade
@if(is_null(($data['books']) || ($data['authors'])))
<h2>Not Found, please try using another search term</h2><br/><br/>
@endif
@foreach($data['books'] as $book)
<a href="{{ route('book', $book->id) }}" target="_blank">
<img src="{{ secure_asset($book->image_url) }}" class="img-responsive" alt="{{$book->image_url}}">
</a>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
@endforeach
@forelse($data['authors'] as $author)
<a href="{{ route('author', $author->id) }}" target="_blank">
<img src="{{ secure_asset($author->image_url) }}" class="img-responsive" alt="{{$author->image_url}}">
</a>
<p class="author"></p>
<h1 class="book-title">{{str_limit($author -> name, 20) }}</h1>
@endforeach
What I am trying to is to say
Not Found, please try using another search term
When the search term can't be found. But this is not working for me
@if(is_null(($data['books']) || ($data['authors'])))
<h2>Not Found, please try using another search term</h2><br/><br/>
@endif
It doesn't return the Not found
Upvotes: 1
Views: 76
Reputation: 10254
That's because even with no resuts, the value of $data['books']
or $data['authors']
is not null, instead it's an empty collection. So you should check the count of results:
@if(!$data['books']->count() || !$data['authors']->count())
<h2>Not Found, please try using another search term</h2><br/><br/>
@endif
or use the isEmpty()
method:
@if($data['books']->isEmpty() || $data['authors']->isEmpty())
<h2>Not Found, please try using another search term</h2><br/><br/>
@endif
also, it should actually be an AND insted of OR, IMO:
or use the isEmpty()
method:
@if($data['books']->isEmpty() && $data['authors']->isEmpty())
<h2>Not Found, please try using another search term</h2><br/><br/>
@endif
Upvotes: 2