I would like to have a "not found"-result if the query has no matches in the database.
Here is my result.blade.php:
#extends('layouts.app')
#section('content')
#foreach ($result as $object)
<div class="container pb-5">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Serial Number: </strong>{{ $object->reference }}</p>
<p><strong>Animal Type: </strong>{{ $object->animal->type->category }}</p>
<p><strong>Farm: </strong>{{ $object->animal->user->name }}</p>
<p><strong>Date Of Birth: </strong>{{ $object->animal->dateOfBirth }}</p>
<p><strong>Farm Location: </strong>{{ $object->animal->user->address->city }}</p>
<p><strong>Clinic: </strong>{{ $object->animal->clinic->user->name ?? 'Was Not Checked by a Clinic' }}</p>
<p><strong>Clinic Location: </strong>{{ $object->animal->clinic->user->address->city }}</p>
<p><strong>Vaccination: </strong>
{{ $object->animal->clinic->vaccine1 ?? 'N/A' }},
{{ $object->animal->clinic->vaccine2 ?? 'N/A'}},
{{ $object->animal->clinic->vaccine3 ?? 'N/A'}},
{{ $object->animal->clinic->vaccine4 ?? 'N/A'}},
{{ $object->animal->clinic->vaccine5 ?? 'N/A'}}</p>
<p><strong>Abattoir House: </strong>{{ $object->user->name }}</p>
<p><strong>Abattoir Location: </strong>{{ $object->user->address->city }}</p>
<p><strong>Slaughtered Date: </strong>{{ $object->created_at }}</p>
<p><strong>Slaughtered Weight: </strong>{{ $object->weight }} Kg</p>
<p><stong>Abattoir Displacement Date</stong>{{ $object->dateOfDisplacement }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3><strong>About </strong>{{ $object->animal->user->name }}</h3>
</div>
<div class="card-body">
<div class="col-12">
<h4 style="font-style: italic; color: gray">{{ $object->animal->user->description ?? 'There is No Details about this farm'}}</h4>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#endsection
As I am looping through the result, I cannot use the "if not"
or my controller. As you can see I tried the "if not" which is not showing anything:
public function getResult($serial_number) {
$result = Slaughter::where('reference', 'like', "%{$serial_number}%")
->with('user', 'animal')
->latest()
->get();
return view('search.result', compact('result'));
}
Any help will be kindly welcome.
You can use forelse
#forelse ($users as $user)
<li>{{ $user->name }}</li>
#empty
<p>No users</p>
#endforelse
Read documentation here
You can check the size of result in view.
#if(sizeof($result))
#foreach ($result as $object)
//whatever you have to do
#endforeach
#else
//else condition
#endif
Or you can use forelse loop
#forelse($result as $object)
// result is found
#empty
// result is not found
#endforelse
You can use the blade if statement: https://laravel.com/docs/5.8/blade#custom-if-statements
So your code could be:
#extends('layouts.app')
#section('content')
#if($result)
#foreach ($result as $object)
// content here
#endforeach
#else
// Not found content here.
#endif
#endsection
#if (count($records) > 0)
#foreach ($result as $object)
//Your logic / printing
#endforeach
#else
No record found
#endif
Related
QUERY:
$recent_posts = Blog::join("categories",'categories.id', '=', 'blogs.category_id')
->where('categories.status', 1)
->orderBy('blogs.id', 'desc')
->take(3)
->get();
Both tables had a created_at column.
At frontend im using this to retrieve the data:
<div class="row justify-content-center">
#foreach ($recent_posts as $recent_post)
<div class="col-md-6 col-lg-4 latest-blog-resp">
<div class="blog-item">
<div class="blog-img">
<a href="{{ url('blog/'.$recent_post->slug) }}">
#if ($recent_post->blog_image == '')
<img src="{{ asset('fibonacci/adminpanel/assets/img/dummy/no_image.jpg') }}" class="img-fluid round-item" alt="blog image">
#else
<img src="{{ asset('fibonacci/adminpanel/assets/img/blog/thumbnail1/'.$recent_post->blog_image) }}" class="img-fluid round-item" alt="blog image">
#endif
</a>
</div>
<div class="blog-inner">
<div class="blog-meta">
<span class="mr-2">
<i class="mdi mdi-calendar-account-outline"></i>{{ __('frontend.by_admin') }}
</span>
<span>
<i class="mdi mdi-calendar-range"></i>{{Carbon\Carbon::parse($recent_post->created_at)->isoFormat('MMMM')}} {{Carbon\Carbon::parse($recent_post->created_at)->isoFormat('DD')}}
</span>
</div>
<h5 class="blog-title">
{{ $recent_post->title }}
</h5>
<p class="blog-desc">{{ $recent_post->short_description }}</p>
<a href="{{ url('blog/'.$recent_post->slug) }}" class="blog-more-link">
{{ __('frontend.read_more') }} <i class="fa fa-angle-right ml-2"></i>
</a>
</div>
</div>
</div>
#endforeach
#if (count($recent_posts) === 3)
<div class="col-12 text-center margin-top-30">
<div class="btn-group">
<a href="{{ url('blog') }}" class="default-button">
{{ __('frontend.view_all') }}
</a>
</div>
</div>
#endif
</div>
THE PROBLEM:
$recent_post->created_at returns the category table creation (created_at) date but we expect to receive the blog table result as created_as (like a post creation data).
Thanks in advance!
Specify your fields in a select clause.
$recent_posts = Blog::select(
'blogs.slug',
'blogs.blog_image',
'blogs.title',
'blogs.short_description',
'blogs.created_at'
)
->join('categories', 'categories.id', 'blogs.category_id')
->where('categories.status', 1)
->orderByDesc('blogs.id')
->take(3)
->get();
I want to have two loops in my view, so I wrote these two functions
public function index()
{
$books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
public function loggedin()
{
$books = Book::orderBy('RAND()')->take(1)->get();
return view('bookpage')->with('books', $books);
}
In the view I have
<!--First Loop -->
#foreach($books as $book)
<div class="col-md-6">
<div class="out-box">
<h2>{{ $book->name }}</h2>
<h3>{{ $book->author->name }}</h3>
<br>
Start Reading<br><br>
<img src="assets/img/cart-buy.png" width="13px"/> Buy
</div>
</div>
</div>
</div>
<div class="col-md-6">
<input id="aboutbook" type="radio" name="tabs" checked>
<label for="aboutbook" class="aboutbook">About This Book</label>
<input id="bookreview" type="radio" name="tabs">
<label for="bookreview" class="bookreview">Reviews</label>
<hr style="background-color:black;">
<section style="padding-top:5px;" id="bookabout" >
<div class="row">
<div class="col-md-12">
<p>{{ $book -> about }}</p>
<h1>About the Author</h1>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-3 col-6">
<img src="assets/img/Ellipse.png" class="rounded-circle" width="120px">
</div>
<div class="col-sm-4 col-md-4 col-6">
<h1>{{ $book->author->name }}</h1>
<h4>{{ $book->author->about }}</h4>
</div>
<div class="col-sm-4 col-md-5">
<div id="learnbtn">
Learn More
</div>
</div>
</div>
</section>
<section style="padding-top:5px;" id="bookabout1" >
jjjjjjj
</section>
</div>
</div>
</div>
#endforeach
</section>
<!--Second Loop -->
#foreach($books as $book)
#if($book->recommended === 1)
<div class="col-1-5">
<div class="home-catalog-image">
<a href="{{ $book->image_url }}" target="_blank">
<!-- <img src="{{ $book->image }}" alt="trending image" /> -->
<img src="{{ $book->image_url }}" class="img-responsive" alt="{{ $book->image_url }}">
</a>
<!-- <img src="{{ asset('/books/'.$book->image) }}" alt="trending image" /> -->
</div>
<p class="author">{{ $book->author->name }}</p>
<h1 class="book-title">{{str_limit($book -> name, 20) }}</h1>
</div>
#endif
#endforeach
In my web.php
Route::get('/', 'WelcomeController#index')->name('welcome');
I want to call another function in the view, although I know the method is wrong, I don't know how to go about it.
You don't have to create two different method for logged in user just use
public function index()
{
if(auth()->user()) {
$books = Book::orderBy('RAND()')->take(1)->get();
} else $books = Book::orderBy('created_at', 'desc')->take(10)->get();
return view('bookpage')->with('books', $books);
}
in view file use
#auth
//code for logged in user
#else
//code for guest user
#endauth
I was able to solve my problem like this
public function loggedin()
{
$data = array();
$data['recommends'] = Book::where('recommended', 1)->take(10)->get();
$data['latests'] = Book::orderBy('created_at', 'desc',)->where('recommended', 0)->take(10)->get();
$data['logged'] = Book::all()->random(1);
return view('index-logged', compact("data"));
}
In my view, I did
#foreach($data['logged'] as $log)
<h1>{{ $log->author->name }}</h1>
<h4>{{ $log->author->about }}</h4>
#endforeach
#foreach($data['recommends'] as $recommend)
<p class="author">{{ $recommend->author->name }}</p>
<h1 class="book-title">{{str_limit($recommend -> name, 20) }}</h1>
#endforeach
#foreach($data['latests'] as $latest)
<p class="author">{{ $latest->author->name }}</p>
<h1 class="book-title">{{str_limit($latest -> name, 20) }}</h1>
#endforeach
I am trying to put a search box in my home.blade but it is not working properly.
Here bellow is my home view
#extends('layouts.app')
#section('content')
<form action="{{ route('home') }}">
<div class="p-1 bg-light rounded rounded-pill shadow-sm mb-4">
<div class="input-group">
<input type="search" name="search" placeholder="Here the animal serial number..." aria-describedby="button-addon1" class="form-control border-0 bg-light">
<div class="input-group-append">
<button id="button-addon1" type="submit" class="btn btn-link text-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</div>
</form>
#foreach($animal as $animal)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $animal->id }}</p>
<p><strong>Animal: </strong>{{ $animal->type->category }}</p>
<p><strong>Gender: </strong>{{ $animal->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $animal->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $animal->user->name }}</p>
<p><strong>Date: </strong>{{ $animal->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#if(request()->has('search') && request()->get('search') != '')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $animal->id }}</p>
<p><strong>Animal: </strong>{{ $animal->type->category }}</p>
<p><strong>Gender: </strong>{{ $animal->gender }}</p>
<p><strong>Place Of Birth: </strong>{{ $animal->user->address->city }}</p>
<p><strong>Farm: </strong>{{ $animal->user->name }}</p>
<p><strong>Date: </strong>{{ $animal->created_at }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endif
#endsection
and my controller
public function index()
{
$animal =Animal::all();
if (request()->has('search') && request()->get('search') != ''){
$animal = $animal->where('serial_number', 'like', "%" .request()->get('search')."%");
}
return view('home', compact('animal'))->with('message', 'Below is the result');
}
It bringing me an error like this
'Property [id] does not exist on this collection instance. (View: /Users/macair13/MeatracProject/resources/views/home.blade.php)'
meaning the animal I have passed in my controller is not worrking.
There are a few problems to work through.
1) You have a variable name collision -
#foreach($animal as $animal)
This will overwrite your collection of animals ($animal) with the first individual animal in that collection. On the next iteration foreach will try to iterate over each element of that single animal. And those elements (like id) don't themselves have properties like id, so you get the error you are seeing.
You should change your variable names to avoid the collision, for example convention would be to use $animals, plural, to indicate it is a collection of more than one. So:
Controller
$animals = Animal::all();
// ...
return view('home', compact('animals')) ...
View
#foreach($animals as $animal)
2) The search code in your controller:
$animal = $animal->where(...);
does not actually get the results. You need to append get(), as shown in the docs:
$animal = $animal->where(...)->get();
3) As #Rwd pointed out in the comments, your view has 2 separate chunks of content, one which looks like it should display a collection of animals (the top one with foreach), and a second which looks like it should display just the search results. Similar to problem 1 above, you have a name collision here - both sections are using $animal. After the foreach loop has finished, $animal is the last animal in the collection of all animals - not your search result.
If I am understanding correctly, you probably want use 2 separate variable names, maybe $animals at the top to list all animals, and then maybe $result to show a single search result.
If that is true, you need to update as follows:
Controller
// For the top list of all animals
$animals = Animal::all();
// For the single search result
$result = false;
if (request()->has('search') && request()->get('search') != ''){
$result = $animal->where(...)->get();
}
// Return them both, separately
return view('home', ['animals' => $animals, 'result' => $result])...;
View
#foreach($animals as $animal)
// ...
#if($result)
{{ $result->id }}
So I have 2 tables.
DirtyEvent model and Event model.
I am retrieving DirtyEvent with Event which works fine
In blade I have:
#if (\Request::is('profile/event'))
#foreach ($events as $event)
#if (empty( $event->image ))
<div class="card-header">
<span class="card-title"> {{($event->title) }}</span>
</div>
#else
<div class="card-image">
<img class="img-responsive" src="{{ $event->image }}"></img>
<span class="card-title"> {{($event->title) }}</span>
</div>
#endif
<div class="card-content">
<p><strong>Starts: </strong>#php echo ($startdate) #endphp - {{$event->startime }}</p>
<br>
#if ($startdate != $enddate)
<p><strong>Ends: </strong>#php echo ($enddate) #endphp - {{$event->endtime }}</p>
<br>
#endif
<p><strong>Description:</strong></p>
<br>
<p>{{$event->description }}</p>
</div>
<div class="card-action">
<i class="fa fa-pencil-square-o fa-2x" aria-hidden="true"></i>
<form method="POST" action={{ url('events/delete/' . $event->id) }}>
{{ method_field('PATCH') }}
{{ csrf_field() }}
<button type="submit" class="delete" style="border:none;"><i class="fa fa-trash-o fa-2x" aria-hidden="true"></i></button>
</form>
</div>
#foreach ($events->publicevents as $eventss)
{{dd($events)}}
#endforeach
#endforeach
However dd($events) gives me:
DirtyEvent Collection -> relations -> publicevents -> Event collection
But, It is saying that publicevents do not exist in current collection.
Controller
public function index()
{
$id = Auth::id();
$events = DirtyEvent::where('user_id', $id)
->with('publicevents')
->get();
return view('events.viewEvent', compact('events'));
}
Model
public function publicevents()
{
return $this->hasMany('App\Event', 'event_id');
}
I guess not all dirty event objects have events. So check this first with empty() or isEmpty() or count():
#if (!empty($event->publicevents))
#foreach ($event->publicevents as $eventss)
{{ $eventss->id }}
#endforeach
#endif
Update
It should be $event->publicevents, not $events->publicevetns.
I have a function witch is getting all properties joining the images tables with orderBy and need to add paginate
here is my function
public function show_all()
{
$properties = PropertyDetail::where('active', 1)->with('propImages')->paginate(15)
->orderBy('id', 'DESC')
->get();
return View::make('portal.properties.view_all', compact('properties'));
}
in my view I got
call_user_func_array() expects parameter 1 to be a valid callback,
class 'Illuminate\Support\Collection' does not have a method 'orderBy'
another thing when I removed the orderBy('id', 'DESC')->get() and I try
it works but when I try to put {{ $prop->links() }} in the view I got
Call to undefined method Illuminate\Database\Query\Builder::links()
here is how my view looks like
#foreach($properties as $prop)
<div class="property col-xs-12 col-sm-6 col-md-4">
<div class="image">
<div class="content imgContainer">
{{ HTML::link('property-details/'.$prop->id, '') }}
#foreach($prop->propImages->slice(0, 1) as $image)
{{ HTML::image('images/propertyImages/'.$image->image, $prop->title) }}
#endforeach
</div>
<div class="price"> OMR. <span class="priceNumber"> {{ $prop->price }}</span></div>
</div>
<div class="title">
<h2>{{ HTML::link('', $prop->title, array('title'=>'$prop->title')) }}</h2>
</div>
<div class="location">{{ trans('location.'.$prop->propLocation->city) }}</div>
<div class="bathrooms">
<div class="content">{{ $prop->bathroom }}</div>
</div>
<div class="bedrooms">
<div class="content">{{ $prop->bedroom }}</div>
</div><!-- /.bedrooms -->
<div class="receptionRoom">
<div class="content">{{ $prop->dining_room }}</div>
</div>
</div>
#endforeach
{{ $prop->links() }}
The correct syntax is:
$properties = PropertyDetail::where('active', 1)
->with('propImages')
->orderBy('id', 'desc')
->paginate(15);