Laravel date range filter - php

I have a form that has a dropdown to select a staff member and a date from and date to field where they can pick their required dates and it should show all the selected staff member's records in that date range but it only shows all the records for that staff member, never in the required date range. This is what I have tried
Controller:
public function vehiclereport()
{
$startDate = '2021/01/01';
$endDate = '2021/12/12';
$energy = VehicleLog::join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')
->join('smsstaff', 'vehicleslog.smsstaff_key', '=', 'smsstaff.smsstaff_key')
->when(request()->input('smsstaff_key'), function ($query) {
$query->where('smsstaff.smsstaff_key', request()->input('smsstaff_key'));
})
->whereDate('log_dt', '>=', $startDate)
->whereDate('log_dt', '<=', $endDate)
->get();
$cars = Vehicle::get();
$staff = Staff::all();
return view('admin.vehiclereport', compact('energy', 'cars', 'staff', 'startDate', 'endDate'));
}
View:
<form>
<select name="smsstaff_key" id="smsstaff_key">
<option></option>
#foreach ($staff as $staffMember)
<option value="{{$staffMember->smsstaff_key}}" {{request()->input('smsstaff_key') === $staffMember->smsstaff_key ? 'selected="selected"' : ''}}>{{$staffMember->name}}</option>
#endforeach
<input type="date" class="form-control" name="startDate">
<input type="date" class="form-control" name="endDate">
</select>
<button>Filter by selected staff member</button>
</form>

There's a few issues here:
(a) You have your inputs inside the select, move them out of the select,
(b) you have the from/to dates in a bad format. They should look like YYYY-MM-DD,
(c) you aren't actually initialising the inputs with those dates i.e. doing something like <input type="date" name="startDate" value="{{ $startDate }}" /> and
(d) You aren't reading the dates from the input you currently have them static.
Try this code instead:
public function vehiclereport()
{
$startDate = request()->input('startDate', '2021-01-01');
$endDate = request()->input('endDate','2021-12-12');
$energy = VehicleLog::join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')
->join('smsstaff', 'vehicleslog.smsstaff_key', '=', 'smsstaff.smsstaff_key')
->when(request()->input('smsstaff_key'), function ($query) {
$query->where('smsstaff.smsstaff_key', request()->input('smsstaff_key'));
})
->whereDate('log_dt', '>=', $startDate)
->whereDate('log_dt', '<=', $endDate)
->get();
$cars = Vehicle::get();
$staff = Staff::all();
return view('admin.vehiclereport', compact('energy', 'cars', 'staff', 'startDate', 'endDate'));
}
and the view:
<form>
<select name="smsstaff_key" id="smsstaff_key">
<option></option>
#foreach ($staff as $staffMember)
<option value="{{$staffMember->smsstaff_key}}" {{request()->input('smsstaff_key') === $staffMember->smsstaff_key ? 'selected="selected"' : ''}}>{{$staffMember->name}}</option>
#endforeach
</select>
<input type="date" class="form-control" name="startDate" value="{{ $startDate }}">
<input type="date" class="form-control" name="endDate" value="{{ $endDate }}">
<button>Filter by selected staff member</button>
</form>

Related

search with pagination is not working in laravel

I make it in 1 route with
in route
Route::get('/all-students', 'AdminController#studentList')->name('admin.student');
Route::post('/all-students', 'AdminController#searchByClassRoll')->name('search-by-class-roll');
in controller funtion student list
public function studentList(Request $request)
{
Session::put('url.intended2', URL::current());
Session::put('url.intended', URL::previous());
if (isset($request->class)) {
if (isset($request->roll)) {
if ($request->class == 'all') {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->orderBy('id', 'DESC')
->paginate(20);
} else {
$students = DB::table('students')
->where('roll', '=', $request->roll)
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
} else {
if ($request->class == 'all') {
return redirect()->route('admin.student');
} else {
$students = DB::table('students')
->where('class', '=', $request->class)
->orderBy('id', 'DESC')
->paginate(20);
}
}
} else {
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
}
return view('admin.student-list')->with('students', $students);
}
post method
public function searchByClassRoll(Request $request)
{
$class = $request->class;
$roll = $request->roll;
if (isset($request->class)) {
if (isset($request->roll)) {
return redirect()->route('admin.student', ['class' => $class, 'roll' => $roll]);
} else {
return redirect()->route('admin.student', ['class' => $class]);
}
}
}
in blade
#if(method_exists($students,'links'))
{!! $students->links() !!}
#endif
normally when I click page 2 it returns
all-students?page=2
when I search something all-students?class=2 and then i click on pagination page it returns again all-students?page=2 and remove the search data from URL.
form from view
<form action="{{ route('search-by-class-roll') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="type" value="student_list">
<div class="row gutters-8">
<div class="col-4-xxxl col-xl-4 col-lg-3 col-12 form-group">
<div class="ui-alart-box">
<div class="default-alart">
<div class="result" role="alert">
#if(app('request')->input('class') || app('request')->input('roll'))
See All<span> | </span>
#endif
Showing results {{$students->count()}} of {{$students->total()}} entries
</div>
</div>
</div>
</div>
<div class="col-3-xxxl col-xl-3 col-lg-3 col-12 form-group">
<input type="number" name="roll" placeholder="Search by Roll..." class="form-control">
</div>
<div class="col-4-xxxl col-xl-3 col-lg-3 col-12 form-group">
<select class="select2 form-control" name="class" required>
<option value="all">All Classes</option>
<option value="baby">baby</option>
<option value="nursery">nursery</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
<option value="5">five</option>
<option value="6">six</option>
<option value="7">seven</option>
<option value="8">eight</option>
<option value="9">nine</option>
<option value="10">ten</option>
</select>
</div>
<div class="col-1-xxxl col-xl-2 col-lg-3 col-12 form-group">
<button type="submit" class="fw-btn-fill btn-gradient-yellow">SEARCH</button>
</div>
</div>
</form>
i want to made this because I want this in 1 URL just because if someone manually entered the URL with search data he can see the output. but in here I can't get the result with pagination from blade. when I turned into page 2 it remove the search variable from URL. and paginate the whole data. how can I get result with pagination after search?
There is the simpler way
Just add with your paginated array.
{{ $users->withQueryString()->links() }}
Coming directly to your controller. You don't need any other route or method you can handle this filtering on same route and in same method.
public function studentList(Request $request)
{
if(!empty($request)){
$query = $request->all();
$students = DB::table('students')->orderBy('id', 'DESC');
if(isset($request->class) AND $request->class != '' AND $request->class != 'all')
$students = $students->where('class', '=', $request->class);
if(isset($request->roll) AND $request->roll != '')
$students = $students->where('roll', '=', $request->roll);
$students = $students->paginate(20);
return view('admin.student-list', compact('students','query'));
}
$students = DB::table('students')
->orderBy('id', 'DESC')
->paginate(20);
return view('admin.student-list', compact('students'));
}
Change few things in your view
<form action="{{ route('admin.student') }}" method="get"> change route and method to get
{{ csrf_field() }} //remove this
Below your table inside view write this code. The appends() is most important otherwise pagination in your filtered data won't work.
#if(isset($query))
{{ $students->appends($query)->links() }}
#else
{{ $students->links() }}
#endif
Try use append on paginator blade
{{$students->appends(\Illuminate\Support\Facades\Input::except('page'))->links()}}

How to select an option from the view and search in the controller? (LARAVEL) [duplicate]

This question already exists:
how to implement a search with many filters that the user chooses in Laravel? [closed]
Closed 2 years ago.
I have a code on my blade template page with a search field and a select with options.
The user types what he wants to search in the search field and selects a search option, which must be sent to the controller to search and return the searched customers according to the selected search option.
The view part is ready, but I am still unable to find a way for the controller to choose this option and do the research accordingly.
My client view page:
<form action="{{ route('search') }}" method="POST" class="form form-inline" role="search">
#csrf
<label class="procurar">Procurar for:</label>
<div class="col-3">
<input type="text" name="nome" class="form-control" placeholder="">
</div>
<label>Filtro: </label>
<div class="form-group">
<select name="busca" class="form-control">
<option value="nome">Nome</option>
<option value="tipo_pessoa">Tipo de Pessoa</option>
<option value="cidade">Cidade</option>
<option value="uf">Estado</option>
<option value="cpf_cnpj">CPF /CNPJ</option>
<option value="tipo_cliente">Tipo de Cliente</option>
<option value="onde_nos_encontrou">Onde nos encontrou</option>
</select>
</div>
</form>
My search function:
public function search(Request $request)
{
if ($request->nome)
{
$nome = $request->nome;
$clients = Client::where('nome', 'like', '%'.$nome.'%')
->orderBy('nome')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
if ($request->uf)
{
$uf = $request->uf;
$clients = Client::where('uf', 'like', '%'.$uf.'%')
->orderBy('uf')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
return redirect()->route('clients.index');
}
Thanks for help!
You need to get the value of busca as that's a select's name. The selected value will be there.
public function search(Request $request)
{
$busca = $request->input('busca', 'nome');
$clients = Client::where($busca, 'like', '%' . $busca . '%')
->orderBy($busca)
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}

Laravel - Form select categories from database

I have database tables 'Events' and 'Categories'.
I want to assign a category to an event using a select dropdown in the form. I also want to be able to edit it and update it. The code I have currently given me the following error -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
'category_id' cannot be null
addEvent.blade.php
<div class="form-group">
<div class="form-group">
<div class="form-group">
{!! Form::Label('category_id', 'Category:') !!}
<select> class="form-control" name="category_id">
#foreach($categories as $category)
<option value='{{ $category->id}}'> {{ $category->category}}</option>
#endforeach
</select>
</div>
</div>
</div>
eventController
public function addEvent(Request $request)
{
$this->validate($request, [
'event_name' => 'required',
'start_date' => 'required',
'end_date' => 'required',
'time' => 'required',
'trip_id' => 'required',
]);
$start_date = Carbon::parse($request['start_date'])->format('Y-m-d');
$end_date = Carbon::parse($request['end_date'])->format('Y-m-d');
$tripCheck = Trip::where('id', $request['trip_id'])
->whereDate('startdate', '<=', $start_date)
->whereDate('enddate', '>=', $start_date)
->whereDate('startdate', '<=', $end_date)
->whereDate('enddate', '>=', $end_date)
->first();
if ($tripCheck) {
$events = new Events;
$trips = Trip::all();
$categories = Categories::pluck('category','id');
$events->category_id = $request['category_id'];
$events->colour = $request['colour'];
$events->event_name = $request['event_name'];
$events->start_date = $request['start_date'];
$events->end_date = $request['end_date'];
$events->time = $request['time'];
$events->address = $request['address'];
$events->notes = $request['notes'];
$events->trip_id = $request['trip_id'];
$events->save();
return redirect('trips')->with('success', 'The new event has been added to your trip')->with('trips', $trips)->withCategories($categories);
} else
{
return redirect('trips')->withErrors(['The dates you added are not within Trip start and end date.']);
}
public function display($id)
{
$categories = Categories::all();
return view('/addEvent')->with('trip_id', $id)->withCategories($categories);
}
editEvent
<div class="form-group"> Category:
<input type="select" name="category" class="form-control" value="{{$events->category}}" placeholder="Category" />
</div>
You are closing your <select> too early. Change
<select> class="form-control" name="category_id">
to
<select class="form-control" name="category_id">
to make it have a name, class etc

how to display only the category which is not applied?

I have categories table and I want to display only the categories which are not available in the business_category table OR the business_category->approved is 2.
My code for that:
<div class="col-md-6">
<select multiple name="categories[]" id="categories" class="form-control #error('categories') is-invalid #enderror" autofocus required>
#foreach($categories as $category)
#foreach($business_categories as $business_category)
#if(($business_category->approved==2) || ($business_category->category_id != $category->id))
<option value="{{$category->id}}">{{$category->name}}</option>
#endif
#endforeach
#endforeach
</select>
</div>
My Code in Controller:
$business_categories = BusinessCategories::join('categories', 'categories.id', '=', 'category_id')
->where('business_id', $id)
->select('categories.name as name', 'approved', 'category_id')
->get();
$categories = Categories::where('parent_id', '0')->select('id', 'name')->get();
return view('admin.businesses.edit', with([
'business_categories' => $business_categories,
'categories' => $categories,
]));
But this code displays the categories which is applied or not applied multiple times.
First, you need a hasMany businessCategories relationship on Categories model:
public function businessCategories()
{
return $this->hasMany(BusinessCategories::class);
}
Your query
Categories::orWhereDoesntHave('businessCategories')
->orWhereHas('businessCategories', function($query) {
$query->where('approved', 2);
})->get();
You can find more eloquent relationship query information here

Laravel: Check on which form submitted the request

On my website, users can display posts created by other users. However, I have 2 select boxes, one for ordering by name or date and the other is ordering by category. The way I have done it is incorrect and I am aware of that. The simple reason for this is that I don't know how to make an if check on which form submitted the request.
Here is my controller method for displaying the events:
public function getEvents(Request $request){
if($request['sort'] == "created_at"){
$posts = Post::orderBy('created_at', 'desc')->get();
}
elseif($request['sort'] == "title"){
$posts = Post::orderBy('title', 'desc')->get();
}
elseif($request['category'] == "sport"){
$post = Post::where('type', '=', 'sport' )->get();
}
elseif($request['category'] == "culture"){
$post = Post::where('type', '=', 'culture' )->get();
}
elseif($request['category'] == "other"){
$post = Post::where('type', '=', 'other' )->get();
}
else{
$posts = Post::orderBy('created_at', 'desc')->get();
}
return view ('eventspage', ['posts' => $posts]);
}
This is currently incorrect, I want it to follow this structure:
if(request submitted by 'sort')
then do this...
elseif(request submitted by 'category')
then do this...
Here is my view containing the 2 select boxes:
<div class="row">
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="category" onchange="this.form.submit()" class="form-control">
<option value="sport">sport</option>
<option value="culture">Culture</option>
<option value="other">Other</option>
</select>
</form>
</div>
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="created_at">Date</option>
<option value="title">Title</option>
</select>
</form>
</div>
</div>
You can have a hidden input in your form with name as formName and the respective values.
Then it's easy to check which form submitted.
//Category form
<input type="hidden" name="formName" value="category">
//Sort form
<input type="hidden" name="formName" value="sort">
Then, in the controller:
if($request['formName'] == 'category') //request submitted by 'category'
//then do this...
elseif($request['formName'] == 'sort') //request submitted by 'sort'
//then do this...
Just be careful not to put too much different code in both conditionals. If you find yourself having two entirely different functions, create an action for each form.

Categories