how to implement Laravel AJAX live search on CRUD management table? - ajax

I have a CRUD table that's holding records of doctors that get
retrieved from the MySQL database. I've been following a few tutorials
and managed to set up AJAX live results search.
Now the problem comes from the fact that the logic is stored in a
Controller. I can succesfully retrieve the details from the database
using '-- foreach($data as $row) --' but I don't know how to retrieve
the CRUD actions ( In this case Delete.The create method is separated
from the table itself. I also can't implement status cell using i)
I've tried putting the actions inside the td'. .'td. tags but I get
Routing errors.
Any help is appreciated.
I have the code for the CRUD actions, images etc..inside
"index.blade.php". They should be somehow implemented in the
controller though. doctor controller
function liveSearchDoctor(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data =Doctor::
where('name', 'like', '%'.$query.'%')
->orWhere('mobile', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->paginate(2);
}
else
{
$data =Doctor::latest()->paginate(2);
}
$total_data = $data->count();
if($total_data > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td class="center"><img src="'.$row->image.'" style="width:40px;height:40px;"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->department->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->mobile.'</td>
//status should be implement here
<td><a class="btn btn-primary" href="'.route('doctors.edit',$row->id).'"><i class="fas fa-edit">Edit</i></a>
//delete form should be implement here
</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_data
);
echo json_encode($data);
}
}
index.blade.php (( Note: The CRUD actions and everything is here
implemented succesfully. I however can't implement delete in the
controller )) here is the index.blade.php
#extends('layout.master')
#section('css')
#endsection
#section('content')
<br>
<div class="br-pagebody">
<div class="br-section-wrapper">
#include('include._message')
<div class="row">
<h6 class="br-section-label">Doctors List</h6>
</div>
<div class="row">
<div class="col-lg-4 ">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search doctor Data" />
</div>
</div>
<div class="col-lg-3 offset-lg-5">
Add New Doctor
</div>
</div>
</br>
<div class="table-responsive">
<table class="table table-bordered table-colored table-dark">
<thead class="thead-colored thead-dark">
<tr>
<th>Image</th>
<th>Doctor Id</th>
<th>Name</th>
<th>Department</th>
<th>Email</th>
<th>mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($doctors as $doctor)
<tr>
<td class="center"><img src="{{URL::asset($doctor->image)}}" style="width:40px;height:40px;"/></td>
<td class="center">{{$doctor->id}}</td>
<td class="center">{{$doctor->name}}</td>
<td class="center">{{$doctor->department->name}}</td>
<td class="center">{{$doctor->email}}</td>
<td class="center">{{$doctor->mobile}}</td>
<td class="center">
#if($doctor->status==1)
<span class="badge badge-success">Active</span>
#else
<span class="label label-danger">Deactive</span>
#endif
</td>
<td class="center">
<a class="btn btn-primary" href="{{route('doctors.edit',$doctor->id)}}">
<i class="fas fa-edit">Edit</i>
</a>
{!! Form::open(['method' => 'DELETE','route' => ['doctors.destroy', $doctor->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
</div><!-- table-wrapper -->
<div class="d-flex justify-content-center">
{!! $doctors->links() !!}
</div>
</div>
</div>
#endsection
#section('js')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
fetch_doctor_data();
function fetch_doctor_data(query = '')
{
console.log(query)
$.ajax({
url:"{{route('search.doctor')}}",
method:"GET",
data:{'query':query},
dataType:'json',
success:function(data)
{
console.log(data)
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_doctor_data(query);
});
});
</script>
#endsection

Related

Laravel CRUD search function

I need your help that how can i make a search function for my laravel crud system?
I would like to make a search function where admins can search about users name and it works like a filter and after the search only shown the users that equals with the search.
admin.users.index (Blade file):
<div class="col-md-4">
<form action="/search" method="GET">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Keresés</button>
</span>
</div>
</form>
</div>
<div class="card">
<table class="table">
<thead>
<tr>
<th scope="col">Profilkép</th>
<th scope="col">Név</th>
<th scope="col">Email</th>
<th scope="col">Telefonszám</th>
<th scope="col">Műveletek</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th scope="row"><img src="/uploads/avatars/{{ $user->avatar }}" style=" width:32x; height:32px; float:left; border-radius:50%; margin-right:25px;"></th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone }}</td>
<td>
<a class="btn btn-sm btn-primary" href=" {{ route('admin.users.edit', $user->id) }}" role="button">Szerkesztés</a>
<button type="button" class="btn btn-sm btn-danger" onclick="event.preventDefault(); document.getElementById('delete-user-form-{{ $user->id }}').submit()">
Törlés
</button>
<form id="delete-user-form-{{ $user->id }}" action="{{ route('admin.users.destroy', $user->id) }}" method="POST" style="display: none;">
#csrf
#method("DELETE")
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
UserController Search function:
public function index(Request $request)
{
if(Gate::denies('logged-in')){
dd('no acces');
}
if(Gate::allows('is-admin')){
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd("adminnak kell lenned");
$users = User::paginate(10);
return view('admin.users.index')
->with([
'users' => $users
]);
}
public function search(Request $request) {
$search = $request->get('search');
$users = User::table('users')->where('name', 'like', '%'.$search.'%')->paginate(10);
return view('admin', ['users' => $users]);
}
And i dont have route in web.php because i dont know how can i solve this. :(
Please help me!
thank you for your reply!
$('.table').DataTable({
"paging": true,
"pageLength": 10,
"scrollY": 850,
"scrollX": true,
"columnDefs": [{
"targets": -1,
"orderable": false,
},
],
"ordering": false,
});
Put this command to javascript.
add this css
https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css
add this js
https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js
this is datatable search without anything. if you want use this method.

Laravel - How to disable submit when any of the title field is null

In my Laravel-5.8, I have a model called Goal:
protected $fillable = [
'id',
'weighted_score',
'title',
'start_date',
'end_date',
];
For the model, I have a controller:
Index Controller
public function index()
{
$userEmployee = Auth::user()->employee_id;
$goals = Goal::where('employee_id', $userEmployee)->get();
return view('goals.index')->with(['goals', $goals);
}
This controller renders this view
view
<div class="card-body">
<div class="table-responsive">
<table class=" table table-bordered table-striped table-hover datatable">
<thead>
<tr>
<th width="8%">
Type
</th>
<th width="11%">
Start Date - End Date
</th>
<th>
Weight(%)
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach($goals as $key => $goal)
<td>
{{$goal->title ?? '' }}
</td>
<td>
{{Carbon\Carbon::parse($goal->start_date)->format('M d, Y') ?? '' }} - {{Carbon\Carbon::parse($goal->end_date)->format('M d, Y') ?? '' }}
</td>
<td>
{{$goal->weighted_score ?? '' }}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="row no-print">
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
</div>
</div>
routes:
Route::resource('goals', 'GoalsController');
Route::get('post/publish_all_posts', 'GoalsController#publish_all_posts')->name('post.publish.all');
Controller function for publish_all_posts()
public function publish_all_posts(){
$unapproved_post = Goal::where('employee_id', $userEmployee)
->update([
'is_approved' => 1
]);
}
For this that displays all the goals for this particular employee:
$goals = Goal::where('employee_id', $userEmployee)->get();
I want the application to only enable this:
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
only when there is no NULL value in the field called title
in
$goals = Goal::where('employee_id', $userEmployee)->get();
How do I achieve this?
Thanks
You could try something like this.
#if(! $goals->pluck('title')->contains(null))
<div class="col-12">
<i class="fas fa-arrow-right"></i> Submit
</div>
#endif
when goals titles not contains null show the link using laravel collection methods. documentation
Hope it helps you.

in laravel pass updated value from view to controller without submit button

I am tiring to store manager auth id, I have view page that contents of user tickets, in my database name called "ticket" in that table I have column name called "ticket_view_by_manager_id" in this column I am trying to store manager auth id, when manager open that ticket that time manager auth id, store in this "ticket_view_by_manager_id" column,
my controller
public function manager_assigned_Chat(Request $request, $ticket_id){
$this->validate($request, [
'ticket_view_by_manager_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input['ticket_view_by_manager_id'] = $request->submit;
$input->save();
}
my route
Route::post('user_ticket_chat{ticket_id}', 'Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat{ticket_id}');
my view "showing all user ticket list"
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<form method="POST" action="{{ route('user_ticket_chat{ticket_id}')}}" enctype="multipart/form-data">
#csrf
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<td style="text-align:center"> {{ $key + 1 }} </td>
<td >{{ $my_tickets_list->ticket_id }}</td>
<td > <input type="hidden" name="submit" value="{{ Auth::user()->staff_id }}" href="ticket_chat{{ $my_tickets_list->ticket_id }}" >{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td >{{$my_tickets_list->created_at->todatestring()}} </td>
<td >{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
<input type="submit" value="Send.">
</form>
</tbody>
</table>
in your web.php
Route::post('user_ticket_chat','Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat');
in your controller
public function manager_assigned_Chat(Request $request){
$this->validate($request,[
'ticket_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input->ticket_view_by_manager_id = Auth::user()->id; // or Auth::user()->staff_id; in your case
$input->save();
}
in blade view add meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
in table :
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<tdstyle="text-align:center"> {{ $key + 1 }} </td>
<td>{{ $my_tickets_list->ticket_id }}</td>
<td class="ticket" data-ticketid="{{ $my_tickets_list->ticket_id}}">{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td>{{$my_tickets_list->created_at->todatestring()}} </td>
<td>{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
</tbody>
</table>
now using Jquery AJAX request :
<script>
$(document).on('click','.ticket',function(){
var ticketID=$(this).attr('data-ticket');
$.ajax({
url:'/user_ticket_chat',
type:'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType:'json',
data:{"ticket_id":ticketID},
success:function(response){
console.log(response);
},
error:function(){
alert('Error');
}
});
});
</script>
You should change your validator. It will be like, Please try this:
$this->validate($request, [
'submit' => 'required',
]);
Because your are not sending any info about ticket_view_by_manager_id from view.
Suggestion: may be your code is not well decorated. If you can please
have a look.

Why is The Entire Body of the Web page loaded to the table instead of the data when retrieving data from the database using ajax in Larvel

I have this table showing all the encashment records, it works fine but when I try to get the rows from the database within a specific range of dates and display it to the same table, the whole body of the webpage is being loaded to the table instead of the rows from the database.
Please see image below:
this is my function from the tableController.php
function encashmentRecord_DateRange(Request $request){
if($request->ajax())
{
$start = $request->get('startDate');
$end = $request->get('endDate');
$data = DB::table('encashment_requests')->whereBetween('date',[$start,$end])->get();
return view('incashment',compact('data'));
}
}
the script in my encashment.blade.php
$(document).ready(function(){
$('#dataTable').DataTable();
$('#start_date').datepicker({
format:'yyyy-mm-dd',
autoclose:true
}).val();
$('#end_date').datepicker({
format:'yyyy-mm-dd',
autoclose:true
}).val();
var range = document.getElementById('btnrange');
range.addEventListener('click',function(){
var start_date = $('#start_date').val();
var end_date =$('#end_date').val();
alert(end_date);
$('#dataTable').DataTable().destroy();
listDateRange(start_date,end_date);
},false);
function listDateRange(startDate,endDate){
$.ajax({
method: 'GET',
url : "{{ route('encashmentRecord.action') }}",
data: {startDate:startDate, endDate:endDate},
success:function(data)
{
alert(data);
$('#dataTable').html(data);
}
})
}
});
If you only need the data, you shouldn't be returning view() from your controller.
Try replacing it with this: return response()->json($data, 200);
I may have found the solution to my problem, though it may look lengthy. But it worked.
I made another view, encashmentRecord.blade, containing only the table, so in the controller, instead of returning the data in the incashment.blade, I returned the data to the new view, encashentRecord.blade and I use "#include('encashmentRecord')" in my incashment.blade to display the table.
encashmentRecord.blade.php
<div class="card-body">
<table id="dataTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Account ID</th>
<th class="sort">Date</th>
<th>Desired Ammount</th>
<th>Destination</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#if(isset($data))
#foreach($data as $row)
<tr>
<td>{{ $row->account_name}}</td>
<td>{{ $row->account_id}}</td>
<td>{{ $row->created_at}}</td>
<td>Php {{ $row->requested_ammount}}</td>
<td>{{ $row->destination}}</td>
<td>{{ $row->status}}</td>
</tr>
#endforeach
#else
<tr>
No Data
</tr>
#endif
</tbody>
</table>
and this is incashment.blade.php
<div class="row">
<div class="col-xl-3 ">
<input type="text" name="query" id="start_date" class="form-control input_daterange">
</div>
<div class="col-xl-3 ">
<input type="text" name="query" id="end_date" class="form-control">
</div>
<div class="col-xl-3 ">
<button class="btn" id="btnrange">Go</button>
</div>
</div>
<div class="card" style="margin-bottom: 0px">
<div class="card-header">
Encashment Record
</div>
<div id="table_data">
#include('tables.encashmentRecord')
</div>
</div>
I just change the view in my return on the controller
return view('tables.encashmentRecord',compact('data'));

Nested html formBuilder with Laravel

cart.blade.php
#extends('master')
#section('content')
<div class="container">
#if(Cart::isEmpty())
<b>The card is empty</b> Shopping now
#else
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>item id</th>
....
</tr>
</thead>
<tbody>
{!! Form::open(["url"=>"/pay"]) !!}
<?php $i = 0; $totalCart_price = 0; ?>
#foreach($cart_total_items as $item)
<tr>
<td>{{ $item['id'] }}</td>
....
<td>
{!! Form::open(["url"=>"/my-cart/".$item['id'], "method"=>"DELETE", "style"=>"display: inline"]) !!}
<button type="submit" class="btn btn-danger" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
{!! Form::close() !!}
</td>
</tr>
<?php $i++; $totalCart_price += Cart::get($item['id'])->getPriceSum(); ?>
#endforeach
</tbody>
</table>
<b>Total price: ${{ $totalCart_price }} {{ Form::hidden("total_price", $totalCart_price) }}</b>
<br><br>
{!! Form::submit('check out (paypal)', ["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
Clear cart
#endif
</div>
#stop
Issue: I can delete any item, but during click check out nothing happens, but when I remove clear item form, check out run successfully.
I want to run two operations, How Can I solve it?
Thanks
You can have several forms in a page but they should not be nested.
As given in html5 working draft:
4.10.3 The form element
Content model:
Flow content, but with no form element descendants.
As far as I know form is just the html tags which can be used to send a group(array) of data at once to the server.
In your case your best bet would be to use the ajax query.(though it would make our page javascript dependent)
Or, as I observed you can just seperate the two form like below:
#extends('master')
#section('content')
<div class="container">
#if(Cart::isEmpty())
<b>The card is empty</b> Shopping now
#else
<table class="table table-condensed table-bordered">
<thead>
<tr>
<th>item id</th>
....
</tr>
</thead>
<tbody>
<<!-- Remove the Form tag from here and insert it below -->>
<?php $i = 0; $totalCart_price = 0; ?>
#foreach($cart_total_items as $item)
<tr>
<td>{{ $item['id'] }}</td>
....
<td>
{!! Form::open(["url"=>"/my-cart/".$item['id'], "method"=>"DELETE", "style"=>"display: inline"]) !!}
<button type="submit" class="btn btn-danger" aria-label="Left Align">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
{!! Form::close() !!}
</td>
</tr>
<?php $i++; $totalCart_price += Cart::get($item['id'])->getPriceSum(); ?>
#endforeach
</tbody>
</table>
<<!-- Remove the Form tag from above and insert it below -->>
{!! Form::open(["url"=>"/pay"]) !!}
<b>Total price: ${{ $totalCart_price }} {{ Form::hidden("total_price", $totalCart_price) }}</b>
<br><br>
{!! Form::submit('check out (paypal)', ["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
Clear cart
#endif
</div>
#stop

Resources