Accessing collection from a relationship - laravel

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.

Related

How do I use 2 variable in foreach in laravel blade

One variable is used for searching and
Another variable is used to display name based on id from DB
public function recorddisplay(Request $request)
{
$search =$request['search'] ??"";
if($search != "")
{
$covidrecord=Covidrecord::where('fullname','LIKE',"%$search%")
->orWhere('province','LIKE',"%$search%")
->orWhere('district','LIKE',"%$search%")
->orWhere('localgovernment','LIKE',"%$search%")->paginate(15);
}
else{
$covidrecord= Covidrecord::paginate(15);
}
$data = compact('covidrecord','search');
$dataCovid=DB::table('coviddeathrecord')
->join('district','coviddeathrecord.district','=','district.id')
->join('province','coviddeathrecord.province','=','province.id')
->join('localgovernment','coviddeathrecord.localgovernment','=','localgovernment.id')
->get(['coviddeathrecord.*','district.district','province.province','localgovernment.localgovernment']);
return view('admin.dashboard.display', compact('dataCovid'))->with($data);
}
This is the blade
#foreach(array_merge($covidrecord,$dataCovid) as $data)
<tr>
<td>
<div class="d-flex px-2 py-1">
<div class="d-flex flex-column justify-content-center">
{{-- <label>{{ $data->fullname }}</label> --}}
<h6 class="mb-0 text-sm">{{$data->fullname}}</h6>
<p class="text-xs text-secondary mb-0">{{$data->gender }} ,{{$data->age }} वर्ष</p>
</div>
</div>
</td>
<td>
<p class="text-xs font-weight-bold mb-0">{{ $address->province }}</p>
<p class="text-xs text-secondary mb-0">{{ $address->district }}, {{$address->localgovernment }}<br/> {{ $data->tole }}</p>
</td>
#endforeach
As I am using array_merge, it is throwing the error
//array_merge(): Expected parameter 1 to be an array, object given
You can pass variables in a compact function:
return view('admin.dashboard.display', compact('data', 'dataCovid'));
Also please see compact function
return like this
return view('website.condo_living.index')->with([
'var1'=>$var1,
'var2'=>$var2,
]);
to use 2 variables in foreach in your blade. It´s better that you pass you data from controller
return view('yourSubFolderView.View')->with('yourVariable')->with('yourVariable')
Also you can use
return view('yourSubFolderView.View')->compact('yourVariable', 'yourVariable')
UPDATE
in this line:
return view('admin.dashboard.display', compact('dataCovid'))->with($data);
change to:
return view('admin.dashboard.display', compact('dataCovid'))->with('data',$data);
and in your blade, you can access to $data or $dataCovid with for-each
in your code was missing your variable name 'data', $data
FYI, the a covidrecord variable returns collections of data and a dataCovid variable that returns an array of data that you have to standardize the types of variables to deal with in the view array only or collection only
I convert the data type to collection of array
and passing collection correctly from your method:
public function recorddisplay(Request $request)
{
$search = $request->get('search') ?? "";
if($search != "") {
$covidrecord = DB::table('covidrecord')->where('fullname','LIKE',"%$search%")
->orWhere('province','LIKE',"%$search%")
->orWhere('district','LIKE',"%$search%")
->orWhere('localgovernment','LIKE',"%$search%")
->paginate(15)
->items();
} else {
$covidrecord= DB::table('covidrecord')->paginate(15)->items();
}
$dataCovid = DB::table('coviddeathrecord')
->join('district','coviddeathrecord.district','=','district.id')
->join('province','coviddeathrecord.province','=','province.id')
->join('localgovernment','coviddeathrecord.localgovernment','=','localgovernment.id')
->get(['coviddeathrecord.*','district.district','province.province','localgovernment.localgovernment']);
$items = collect($users)->concat($data);
return view('admin.dashboard.display', compact('items'));
}
and within the blade you can looping normal with collection of array like:
#foreach($items as $data)
<tr>
<td>
<div class="d-flex px-2 py-1">
<div class="d-flex flex-column justify-content-center">
{{-- <label>{{ $data['fullname'] }}</label> --}}
<h6 class="mb-0 text-sm">{{$data['fullname']}}</h6>
<p class="text-xs text-secondary mb-0">{{$data['gender'] }} ,{{$data['age'] }} वर्ष</p>
</div>
</div>
</td>
<td>
<p class="text-xs font-weight-bold mb-0">{{ $address->province }}</p>
<p class="text-xs text-secondary mb-0">{{ $address->district }}, {{$address->localgovernment }}<br/> {{ $data['tole'] }}</p>
</td>
#endforeach

Laravel search from multi select dropdown

I am trying to create a search filter using dropdown selections. The code only shows results when all dropdowns (make and model) are selected. But it should work even single dropdown (either make or model)is selected. At the moment, if I select a single dropdown, the result page shows "No Matching Data found". this is what I have done -
Controller
class CarFrontController extends Controller
{
public function index_classiccars(Request $request)
{
$filterMakes = DB::table('cars')->select('make')->distinct()->get()->pluck('make');
$filterModels = DB::table('cars')->select('model')->distinct()->get()->pluck('model');
$classiccar = Car::query();
if ($request->has('make')) {
$classiccar->where('make', $request->make);
}
if ($request->has('model')) {
$classiccar->where('model', $request->model);
}
return view(
'layouts.frontend.cars.classiccars_index',
[
'filterMakes' => $filterMakes, 'filterModels' => $filterModels,
'classiccars' => $classiccar->get()
]
);
}
public function store(Request $request)
{
return $request->all();
return view('layouts.frontend.cars.classiccars_index');
}
}
data blade
#forelse ($classiccars as $car)
<div class="row">
<div class="col-lg-5 col-md-5 col-pad">
<div class="car-thumbnail">
<a href="car-details.html" class="car-img">
<div class="price-box">
<span>£{{ $car->price }}</span>
</div>
#php $i=1; #endphp
#foreach ($car->join_caralbum as $image)
#if ($i>0)
<img class="d-block w-100" src="{{asset($image->image_location)}}" alt="car" height="225px" >
#endif
#php $i--; #endphp
#endforeach
</a>
<div class="carbox-overlap-wrapper">
<div class="overlap-box">
<div class="overlap-btns-area">
<a class="overlap-btn" href="{{ url('car_show/'.$car->id) }}">
<i class="fa fa-eye-slash"></i>
</a>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-7 col-md-7 col-pad align-self-center">
<div class="detail">
<h3 class="title">
{{ $car->make }}
</h3>
<ul class="custom-list">
<li>
{{ $car->model }} /
</li>
......
</ul>
<ul class="facilities-list clearfix">
.....
.....
....
</ul>
</div>
</div>
</div>
</div>
#empty
No matching data found
#endforelse
filter blade
{!! Form::open(['action'=>'CarFrontController#index_classiccars','method'=>'GET']) !!}
<select class="form-control" name="make" id="make">
<option> Make(All)</option>
#foreach ($filterMakes as $make)
<option value="{{ $make }}">{{ $make }}</option>
#endforeach
</select><br>
<select class="form-control" name="model" id="model">
<option> Model(All)</option>
#foreach ($filterModels as $model)
<option value="{{ $model }}">{{ $model }}</option>
#endforeach
</select><br>
{{ Form::submit('Update Search',['class'=>'btn btn-primary']) }}
Your query results empty because even if you don't select any of your options, you actually do. If options don't have a value, the value is the text you give it to the option.
In your case, if you select just a model, actually you are selected 'Make(All)' option too. You can see this simply by putting dd($request->all()) on your index_classiccars method.
For checking selects, you can give empty value to first(default) option and control it with request()->filled('input').

How to get a 'Not Found' result after searching in laravel

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

How to work with pagination in Laravel Algolia search

Pagination is not working. It shows empty page on clicking 2 page.It is not fetching the second page from the search query. And also token is not showing on
2nd page url. Is this is the reason then how to add csrf_token to pagination
Route.
I am using algolia to search
Route::get('posts/search','PostController#search')->name('posts.search');
Controller
public function search(Request $request){
if($request->has('q')) {
$request->flashOnly('q');
$results = Post::search($request->q)->paginate(5);
} else {
$results = [];
}
return view('posts.search')->with('results', $results);
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Search for Posts</h1>
<form action="{{ route('posts.search') }}" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" name="q" class="form-control input-lg" placeholder="Search for a post..." value="{{ old('q') }}"/>
<span class="input-group-btn">
<button class="btn btn-default btn-lg" type="submit">Search</button>
</span>
</div>
</form>
<hr />
#foreach ($results as $post)
<div class="row" style="margin-top: 20px;">
<div class="col-md-8">
<h3>{{ $post->title }}</h3>
</div>
<div class="col-md-4">
#if ($post->published)
<h4><span class="label label-success pull-right">PUBLISHED</span><h4>
#else
<h4><span class="label label-default pull-right">DRAFT</span><h4>
#endif
</div>
</div>
<div class="row">
<div class="col-md-12">
<p>
{{ str_limit($post->content, 250) }}
</p>
</div>
</div>
#endforeach
#if (count($results) > 0)
<hr />
<div class="text-center">
{{ $results->links() }}
</div>
#endif
#endsection
Try this one may be help
// Making sure the user entered a keyword.
if($request->has('q')) {
// Using the Laravel Scout syntax to search the posts table.
$results = Post::search($request->get('q'))->paginate(15);
}
Update my answer sometimes help this
return view('posts.search',['results' => $results]);
Try :
{{$results->appends(request()->query())->links()}}
insted of
{{ $results->links() }}

Property [articles] does not exist on this collection instance. laravel 5.4

help or assist as it does not turn out to make sorting on categories, I can not understand as to solve this problem.
I recently study laravel.
Controller: class ArticlesController
public function showAll ($category_id)
{
$categories = Category::where('name', $category_id)->get();
return view('categories')->with(compact('categories', 'articles'));
}
This view from which I want to go into categories. site.blade.php
#foreach($categories as $category)
<li><a class="nav-link text-white" href={{route('articlesShow', ['id'=>$category->id]) }}">{{ $category->name }}</a></li>
#endforeach
Route:
Route::get('/categories/{category_id}', 'ArticlesController#showAll')->name('articlesShow');
Model: Category
public function articles()
{
return $this->hasMany(Article::class, 'category_id');
}
Representation in which does not get to get: categories.blade.php
#foreach($categories->articles as $article)
<div class="col-6 col-lg-4"> <!--Post -->
<img src="{{ asset('upload/image/1.jpg') }}" width="255" alt="..." class="rounded img_size">
<h4> {{ $article->title }}</h4>
<h6>Category: {{ $article->category->name }}</h6>
<h6>Author: {{ $article->author }}</h6>
<p>{{ $article->text }} </p>
<p><a class="btn btn-secondary" href="{{ route('articleShow', ['id' =>$article->id]) }}"> More »</a></p>
</div><!--EndPost-->
#endforeach
$categories is an array that contains categories, and the articles property belongs to a category, therefore you have to loop the categories before you can access the articles.
try this:
#foreach($categories as $category)
#foreach($category->articles as $article)
<div class="col-6 col-lg-4"> <!--Post -->
<img src="{{ asset('upload/image/1.jpg') }}" width="255" alt="..." class="rounded img_size">
<h4> {{ $article->title }}</h4>
<h6>Category: {{ $article->category->name }}</h6>
<h6>Author: {{ $article->author }}</h6>
<p>{{ $article->text }} </p>
<p><a class="btn btn-secondary" href="{{ route('articleShow', ['id' =>$article->id]) }}"> More »</a></p>
</div><!--EndPost-->
#endforeach
#endforeach
First of all: use eager loading.
Assuming, your ArticlesController#showAll method should display all articles for a given category id, your query should look like this
public function showAll ($category_id)
{
$categoryArticles = Category::with('articles')->where('id', $category_id)->get();
return view('categories')->with('categoryArticles', $categoryArticles);
}
Then to display all articles for the given category (assuming an article has only one category), this could be one way:
#foreach($categoryArticles->articles as $article)
<div class="col-6 col-lg-4"> <!--Post -->
<img src="{{ asset('upload/image/1.jpg') }}" width="255" alt="..." class="rounded img_size">
<h4> {{ $article->title }}</h4>
<h6>Category: {{ $categoryArticles->name }}</h6>
<h6>Author: {{ $article->author }}</h6>
<p>{{ $article->text }} </p>
<p><a class="btn btn-secondary" href="{{ route('articleShow', ['id' =>$article->id]) }}"> More »</a></p>
</div><!--EndPost-->
#endforeach

Resources