How do I use 2 variable in foreach in laravel blade - laravel

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

Related

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').

Undefined variable: product_item in laravel

I want to update selected items and this is my code:
controller:
public function updatesyncFiles(Request $request , $id){
$product_item = Singleproduct::find($id);
$files = $request->input('files');
if ($product_item && is_array($files)){
$product_item->file()->sync($files);
}
}
blade:
#if( $files && count($files) > 0)
<form action="{{ route('product.sync_files' , $product_item ) }}" method="post">
{{ csrf_field() }}
<h3 style="color: black; ">فایل مربوطه:</h3>
<section class="panel">
<table class="table table-striped table-advance table-hover">
<ul>
#foreach($files as $file)
<li>
<input type="checkbox" name="files[]" value="{{ $file->file_id }}" {{ isset($id) && in_array($file->id,$id) ? 'checked':'' }}>
{{ $file->file_name }}
</li>
#endforeach
</ul>
<div class="form-group">
<input type="submit" class="btn btn-danger" name="submit_product_files" value="ذخیره اطلاعات">
</div>
</table>
</section>
</form>
#endif
and the error is: "Undefined variable: product_item"
what is the problem??
You should pass your variables to the view like this:
return view('your_view', [
'product_item' => $product_item
]);
Also not that you should pass an array to 2nd argument of the route method:
{{ route('product.sync_files', ['product_id' => $product_item]) }}

How to retrieve specific column data from model bind show method?

I'm setting up a new project and want to retrieve data from passed model binding controller show method but output in show view is null
model :
class Content extends Model
{
protected $fillable = ['title','body'];
}
this is my controller :
public function show(Content $content)
{
return view('content.show',compact('content'));
}
this is my index :
#foreach ($content as $item)
<td>
<a class="btn btn-primary" href="{{ route('Content.show',$item) }}">View</a>
</td>
#endforeach
and this is show method that result is null:
<div class="card-header">
{{ $content->title }}
</div>
<div class="card-body">
{{ $content->body }}
</div>
<div class="card-footer">
{{ $content->created_at }}
/div>
i expect have result in show method because everything is okay but there isn't where is my problem ?
Updated :
dd($content)
because you try to get $content while it is $item now :)
<div class="card-header">
{{ $item->title }}
</div>
<div class="card-body">
{{ $item->body }}
</div>
<div class="card-footer">
{{ $item->created_at }}
</div>
I found the answer
I changed the route resource from resource('Content','ContentController') to
resource('content','ContentController') and the problem has been fixed !
i dont know why !
//used to show a list, like what you are trying to do
public function index()
{
$contents = Content::get();
return view('content.index',compact('contents'));
}
//used to show one item
public function show(Content $content)
{
return view('content.show',compact('content'));
}
What you have for you view works if you are looping over multiple content, otherwise you want:
{{ $content->title }}
</div>
<div class="card-body">
{{ $content->body }}
</div>
<div class="card-footer">
{{ $content->created_at }}
</div>```

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

Accessing collection from a relationship

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.

Resources