I am new in the web programming subject. I am doing a project using laravel and Blade for the views, and I want to create an X-editable table for one of my databases so the user doesn't need to enter to a different view to edit the data.
Anyway, I am having a lot of trubbles.
I have this database in mysql:
MySql database
Route
I am doing this in the web.php file that is in the file routes
Route::resource('/test','PruebaController');
Route::get('/test', 'PruebaController#index')->name('test');
Route::post('test/updatetest','PruebaController#updatetest')->name('updatetest');
Controller
public function index(Request $request)
{
if ($request){
$test=DB::table('pruebas')
->orderBy('nombre','asc')
->get();
$test_model = new Prueba();
$fillable_columns = $test_model->getFillable();
foreach ($fillable_columns as $key => $value)
{
$test_columns[$value] = $value;
}
return view('test.index')
->with('test', $test)
->with('test_columns', $test_columns);
}
}
public function updatetest(Request $request, $id)
{
try
{
$id =$request->input('pk');
$field = $request->input('name');
$value =$request->input('value');
$test = Prueba::findOrFail($id);
$test->{$field} = $value;
$test->save();
}
catch (Exception $e)
{
return response($e->intl_get_error_message(), 400);
}
return response('',200);
}
View
#extends ('layouts.admin')
#section ('contenido')
<div class="panel-heading">
<h4>
Listado de nombres
</h4>
#if (count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="panel-body">
<form action="{{route('updatetest')}}" method="post">
{{csrf_field()}}
<table class="table table-hover nowrap" id="example" width="100%">
<thead class="thead-default">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Cédula</th>
<th>Edad</th>
</tr>
</thead>
#foreach ($test as $t)
<tbody>
<tr>
<td>{{$t->id}}</td>
<td>
<a
href="#"
class="nombre"
data-type="text"
data-pk="{{$t->id}}"
data-value="{{$t->nombre}}"
data-title="Cambie el nombre"
data-url="{{route('updatetest') }}">
{{$t->nombre}}
</a>
</td>
<td>
<a
href="#"
class="cedula"
data-type="number"
data-pk="{{$t->id}}"
data-value="{{$t->cedula}}"
data-title="Cambie la cedula"
data-url="{{route('updatetest') }}">
{{$t->cedula}}
</a>
</td>
<td>
<a
href="#"
class="edad"
data-type="number"
data-pk="{{$t->id}}"
data-value="{{$t->edad}}"
data-title="Cambie la edad"
data-url="{{route('updatetest') }}">
{{$t->edad}}
</a>
</td>
</tr>
</tbody>
#endforeach
</table>
</form>
</div>
#endsection
AJAX script
<script type="text/javascript">
$(document).ready(function() {
//toggle `popup` / `inline` mode
$.fn.editable.defaults.mode = 'inline';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
id = $(this).data('pk');
url = $(this).data('url');
//make username editable
$('.nombre').editable({
url: url,
pk: id,
type:"text",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
$('.cedula').editable({
url: url,
pk: id,
type:"number",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
$('.edad').editable({
url: url,
pk: id,
type:"number",
validate:function(value){
if($.trim(value) === '')
{
return 'This field is required';
}
}
});
});
</script>
The problem is that the x-editable is not working, when I click on the field nothing happens. Any idea why is that?
I would really appreciate your help.
Change
<form action="{{route('test/updatetest')}}" method="post">
To
<form action="{{route('updatetest')}}" method="post">
The route function generates a URL for the given named route:
$url = route('routeName');
You can read more about it here
Related
So when I put a route name with a single parameter it works flawlessly but when I pass named route with two parameters I get a 500 error in my console which looks like this:GET http://127.0.0.1:8000/admin/packages/package-programs/kathmandu/action?query= 500 (Internal Server Error).
<?php
namespace App\Http\Controllers\AdminVisible;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Program;
use App\Package;
use DB;
class PackageProgramController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index($packageSlug)
{
$showCounts = Program::count();
$packages = Package::firstOrFail();
return view('admin.pages.packageprogram',compact('showCounts','packageSlug','packages'));
}
function action($packageSlug,Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('programs')
->where('id', 'like', '%'.$query.'%')
->orWhere('day', 'like', '%'.$query.'%')
->orWhere('Package_Type', 'like', '%'.$query.'%')
->orWhere('title', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->get();
}
else
{
$data = DB::table('programs')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$packageProgram = ['packageProgram' => $row->id];
$route = route('PackageProgram.edit',['packageSlug' => $packageSlug, 'packageProgram' => $packageProgram]);
$output .= '
<tr>
<th scope="row"><input type="checkbox" name="ids[]" class="selectbox" value="'.$row->id.'" onchange="change()"></th>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->id.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->day.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->title.'</td>
<td onClick="location.href=\''.$route.'\' " style="cursor: pointer">'.$row->description.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="12">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
public function create($packageSlug, Package $package)
{
return view('admin.create.createPackageProgram',compact('packageSlug','package'));
}
public function store($packageSlug,Request $request)
{
$packages = Package::where('slug', $packageSlug)->firstOrFail();
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packages->program()->create($data);
switch ($request->input('action')) {
case 'preview':
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been added.');
break;
default:
return redirect()->back()->with('message', 'Package Program has been added.');
break;
}
}
public function edit($packageSlug,Program $packageProgram,Package $package)
{
return view('admin.edit.editPackageProgram',compact('packageSlug','packageProgram','package'));
}
public function update($packageSlug, Program $packageProgram)
{
$data = request()->validate([
'day' => 'required',
'title' => 'required',
'description' => 'required',
]);
$packageProgram->update($data);
return redirect()->intended(route('PackageProgram',$packageSlug))->with('message', 'Package Program has been updated.');
}
public function delete(Request $request) {
$data = request()->validate([
'deleteSelected' => 'required',
]);
$id = $request->get('ids');
$data = DB::delete('delete from programs where id in ('.implode(",",$id).')');
return redirect()->back()->with('message', 'Testimony has been deleted.');
}
}
My blade file looks something like this:
#extends('layouts.app')
#section('style')
<link href="{{ asset('css/Admin/sql-data-viewer.css') }}" rel="stylesheet">
<style></style>
#endsection
#section('content')
<section class="data-viewer">
<div class="d-flex justify-content-between px-3">
<h3 class="text-white">Select {{$package->Package_Name}} {{$package->Package_Type}} Days to change</h3>
<button type="button" class="btn add-data text-white rounded-pill">Add Day <i class="fas fa-plus"></i></button>
</div>
<form>
#csrf
#method('DELETE')
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
<div class="d-flex justify-content-between selectDelete">
<div class="delete pl-3 mt-3 mb-3">
<label for="deleteSelected">Action:</label>
<select name="deleteSelected" id="deleteSelected" class="#error('deleteSelected') is-invalid #enderror" name="deleteSelected" >
<option disabled selected>---------</option>
<option>Delete Selected Package Program</option>
</select>
<button formaction="{{ route('PackageProgram.delete',$package) }}" formmethod="POST" type="submit" class="go" id="deleleGo" onclick="deleteBtn()">Go</button>
<span id="selected">0</span> of {{$showCounts}} selected
#error('deleteSelected')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<strong id="selectError">You must check at least one checkbox</strong>
</div>
<div class="search pr-3 mt-3 mb-3">
<label for="search">Search:</label>
<input id="search" type="text" color="#000" class="rounded #error('search') is-invalid #enderror" name="search" value="{{ old('search') }}" autocomplete="search" placeholder="Search">
#error('search')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<table class="table table-hover table-striped table-dark">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</form>
</section>
#endsection
#section('script')
<script src="{{ asset('/js/sqlData.js') }}"></script>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data(query = '')
{
$.ajax({
url:"{{ route('PackageProgram.action',$packageSlug) }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_data(query);
});
});
function checkboxError(){
var number = document.querySelectorAll('.selectbox:checked').length;
if(number == 0) {
var a = document.getElementById("selectError").style.display = "block";
return false;
}
}
window.addEventListener('DOMContentLoaded', (event) => {
var deleteBtn = document.getElementById("deleleGo");
deleteBtn.onclick = checkboxError;
});
</script>
#endsection
So my route file looks something like this:
Route::prefix('package-programs')->group(function() {
Route::get('/', 'AdminVisible\packagePackageProgramController#index')->name('PackagePrograms');
Route::get('/action', 'AdminVisible\packagePackageProgramController#action')->name('PackagePrograms.action');
Route::prefix('{packageSlug}')->group(function() {
Route::get('/', 'AdminVisible\PackageProgramController#index')->name('PackageProgram');
Route::get('/action', 'AdminVisible\PackageProgramController#action')->name('PackageProgram.action');
Route::get('/create', 'AdminVisible\PackageProgramController#create')->name('PackageProgram.create');
Route::post('/create', 'AdminVisible\PackageProgramController#store')->name('PackageProgram.store');
Route::delete('/delete','AdminVisible\PackageProgramController#delete')->name('PackageProgram.delete');
Route::get('/{packageProgram}/edit', 'AdminVisible\PackageProgramController#edit')->name('PackageProgram.edit');
Route::patch('/{packageProgram}', 'AdminVisible\PackageProgramController#update')->name('PackageProgram.update');
});
});
It might be I do not know how to pass named route with two parameters but in my blade file, I been doing it like this, and there it works. Is it something different that must be done in the controller.
First start from blade (please check comments):
#extends('layout')
#section('content')
<div class="row">
<table class="table table-hover table-striped table-dark" id="slugTb">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: "{{ route('test.action') }}",
method: 'GET',
data: {
'slug': '{{ $packageSlug }}',
'query': query
},
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
#endsection
You used deprecated jquery method like success check
Better use this three: done,fail,always
Next route web.php:
Route::get('action', ['as' => 'test.action', 'uses' => 'TestController#action']);
In your case better to use Request params bag so that you can add as much params as you want.
Next controller:
function action(Request $request)
{
$total_row = 1;
$packageSlug = $request->get('slug'); //names that you set in ajax data tag: {'slug': '{{ $packageSlug }}','query': query}
$query = $request->get('query');
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
You should return something from the controller so blade can show that data and json encode it so that js could parse it. That is why return response()->json($data);
Other way:
route:
Route::get('/action/{slug}/{query}',['as' => 'test.action', 'uses' => 'TestController#action']);
blade script:
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: 'action/{{ $packageSlug }}/' + query,
method: 'GET',
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
and controller:
function action($slug, $query)
{
$total_row = 1;
$packageSlug = $slug;
$query = $query;
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
Not recommended just because you manually type route in ajax request: url: 'action/{{ $packageSlug }}/' + query if your route changes you have to change it in js.
I am using laravel 7. In my CRUD application, I am having trouble deleting a user record. I have tried a variety of methods which I have left commented out so that you can see what I tried. I am using Sweetalert2 for the confirmation call and when I click confirm, it redirects to the correct page but I do not get a success message nor is the record deleted from the database. I am new to Laravel so if anyone can spot where I may have gone wrong, I would sure appreciate it.
Here are the following relevant codes.
(EDIT OF CODE BELOW!!!)
index.blade.php
#extends('layouts.admin')
#section('content')
<div class="container-fluid mt-5">
<!-- Heading -->
<div class="card mb-4 wow fadeIn">
<!--Card content-->
<div class="card-body d-sm-flex justify-content-between">
<h4 class="mb-2 mb-sm-0 pt-1">
Inicio
<span>/</span>
<span>Registered Users</span>
</h4>
</div>
</div>
<!-- Heading -->
<!--Grid row-->
<!--Grid column-->
<div class="row">
<!--Card-->
<div class="col-md-12 mb-4">
<!--Card content-->
<div class="card">
<!-- List group links -->
<div class="card-body">
<h5>Users Online:
#php $u_total = '0'; #endphp
#foreach ($users as $user)
#php
if($user->isUserOnline()) {
$u_total = $u_total + 1;
}
#endphp
#endforeach
{{ $u_total }}
</h5>
<table id="datatable1" class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th class="text-center">Online/Offline</th>
<th class="text-center">Banned/Unban</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<input type="hidden" name="id" value="{{ $user->id }}">
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role_as }}</td>
<td>
#if($user->isUserOnline())
<label class="py-2 px-3 badge btn-success" for="">Online</label>
#else
<label class="py-2 px-3 badge btn-warning" for="">Offline</label>
#endif
</td>
<td>
#if($user->isBanned == '0' )
<label class="py-2 px-3 badge btn-primary">Not Banned</label>
#elseif($user->isBanned == '1')
<label class="py-2 px-3 badge btn-danger">Banned</label>
#endif
</td>
<td>
<a class="badge badge-pill btn-primary px-3 py-2" href="{{ url('role-edit/'.$user->id) }}">Editar</a>
<a class="delete badge badge-pill btn-danger px-3 py-2" data-toggle="modal" href="{{ url('user-delete/'.$user->id) }}" data-target="#delete" data-id="{{ $user->id }}">Borrar</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{-- <div>
{{ $users->links() }}
</div> --}}
</div>
<!-- List group links -->
</div>
</div>
<!--/.Card-->
</div>
<!--Grid row-->
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal.fire({
title: "¿Estás Seguro/a?",
text: "¡No podrás revertir esto!",
icon: 'warning',
showCancelButton: true,
cancelButtonText: 'Cancelar',
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí, Borralo!'
},
function() {
$.ajax({
type: "POST",
url: "{{url('/user-delete/{id}')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
});
</script>
#endsection
Within my web.php (relevant code only)
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/dashboard', function () {
return view('admin.dashboard');
});
Route::get('registered-user', 'Admin\RegisteredController#index');
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#destroy');
Route::get('registered-empresa', 'Admin\EmpresaController#index');
Route::get('registered-empleado', 'Admin\EmpleadoController#index');
Route::get('role-edit/{id}', 'Admin\RegisteredController#edit');
Route::put('role-update/{id}', 'Admin\RegisteredController#updaterole');
Route::post('save-empresa', 'Admin\EmpresaController#store');
Route::get('/edit-empresa/{id}', 'Admin\EmpresaController#edit');
Route::put('/empresa-update/{id}', 'Admin\EmpresaController#update');
Route::get('/edit-empleado/{id}', 'Admin\EmpleadoController#edit');
Route::put('/empleado-update/{id}', 'Admin\EmpleadoController#update');
Route::post('save-empleado', 'Admin\EmpleadoController#store');
});
RegisteredController.php (delete function only)
public function destroy(Request $request, $id)
{
// $user = User::findOrFail($id)->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
// $user = User::find($id);
// $user->delete();
// return redirect()->back()->with('status', 'Usuario ha sido borrado.');
User::destroy($id);
}
EDIT!!!
I changed the way I am calling the sweetalert2 but am still getting errors. I changed my delete button in index.blade.php to
<a class="delete badge badge-pill btn-danger px-3 py-2" onclick="deleteConfirmation({{ $user->id }})">Borrar</a>
In the same file, I changed the script to the following:
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: !0,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar",
reverseButtons: !0
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("Done!", results.message, "success");
} else {
swal.fire("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I also removed the .ready function as it was causing a conflict with sweetalert2
My Delete function in my RegisteredController now looks like this:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
}
And in my web.php, I changed the route to:
Route::post('/user-delete/{id}', 'Admin\RegisteredController#delete');
The sweet alert now pops up and when I click delete, I get the console error:
POST http://ecomsivendo.test/user-delete/4 419 (unknown status)
You also need the headers section for jquery ajax calls.
$.ajax({
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//.......
Also make sure you have the meta tag in the <head> on the page.
<meta name="csrf-token" content="{{ csrf_token() }}">
Thank you for all those who tried to help me on this. I ended up giving the code another overhaul and this is what I had to do to get it to work.
I had to change my ajax request in the index.blade.php
function deleteConfirmation(id) {
swal.fire({
title: "Borrar?",
text: "¿Estás seguro/a?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Sí,Borralo!",
cancelButtonText: "Cancelar"
}).then(function (e) {
if (e.value === true) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'POST',
url: "{{url('/user-delete')}}/" + id,
headers: {
'X-CSRF-TOKEN': '<?php echo csrf_token() ?>'
},
data: {"id": id, _method: 'delete'},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal.fire("¡Hecho!", results.message, "success");
setTimeout(function() {
location.reload();
}, 1000);
} else {
swal.fire("¡Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
I am not happy with the setTimout function to get the page to reload and if someone can offer a better solution to avoid reload, I would really appreciate it.
in the controller, I had to change the delete function to the following:
public function delete($id)
{
$delete = User::where('id', $id)->delete();
// check data deleted or not
if ($delete == 1) {
$success = true;
$message = "Usuario borrado exitosamente";
} else {
$success = true;
$message = "Usuario no encontrado";
}
// Return response
return response()->json([
'success' => $success,
'message' => $message,
]);
}
And finally in my web.php, I have the route as:
Route::delete('/user-delete/{id}', 'Admin\RegisteredController#delete');
like I mentioned earlier, I feel like the setTimeout is a hack and I would prefer something a bit more elegant.
In the end, the code does what it is supposed to do and that is delete the entry and update the view.
I'm trying to create Live search in Laravel using AJAX with one of my tables. I watched a YouTube video on this and I got to around 18:00 min on the 21 minute video. At this point there was no LIVE search, but he was able to view the data in his table through the AJAX request. While the video wasn't perfect, I wasn't seeing the data appear in my table, I am getting the response, I see the data in the network tab, in the response tab of my console, but am unable to see it displayed on the web page, and I'm not getting any other errors.
web.php:
Route::get('/admin/job-seeker/search', 'AdminJobSeekerSearchController#index')->name('admin.job.seeker.search.index')->middleware('verified');
Route::get('/admin/job-seeker/search/action', 'AdminJobSeekerSearchController#action')->name('admin.job.seeker.search.action')->middleware('verified');
AdminJobSeekerSearchController.php:
public function index()
{
return view('admin.job-seeker.search.index'));
}
public function action(Request $request)
{
if($request->ajax())
{
$total_data = '';
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('employer_profiles')
->where('company_name', 'like', '%'.$query.'%')
->orWhere('company_address', 'like', '%'.$query.'%')
->orWhere('immediate_contact', 'like', '%'.$query.'%')
->get();
}
else
{
$data = DB::table('employer_profiles')
->orderBy('id', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->company_name.'</td>
<td>'.$row->company_address.'</td>
<td>'.$row->immediate_contact.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
$str_data = implode(" ", $data);
echo $str_data;
}
}
index.blade:
#extends('layouts.admin')
#section('content')
#if (session('send-profile'))
<div class="alert alert-success">
{{ session('send-profile') }}
</div>
#endif
<div class="row">
<div class="col-md-12">
<!-- Topbar Search -->
<form class="navbar-search">
<div class="input-group">
<input type="text" class="form-control bg-lightblue border-0 small text-white border-dark" name="search" id="search" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-success" type="button">
<i class="fas fa-cannabis"></i>
</button>
</div>
</div>
</form><br>
</div>
<div class="col-md-12">
<table class="table table-hover table-responsive-sm">
<thead class="thead-dark">
<tr>
<th scope="col">Total Data : <span id="total_records"></span></th>
<th scope="col">Company Name</th>
<th scope="col">Immediate Contact</th>
<th scope="col">Address</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
#stop
#push('scripts')
<script>
$(document).ready(function() {
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('admin.job.seeker.search.action') }}",
method: 'GET',
data: {query:query},
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
});
</script>
#endpush
The data from the table is supposed to be displayed inside of the <tbody></tbody> tags. Below is a screenshot of the data in my network tab, in the response tab in my console.
Try to return the $data array like this:
return response()->json($data);
I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>
I'm currently developing a comment function in Laravel 5. I want to display instantly the comment the user just post. So how can I achieve that? I have tried to use load() method in AJAX, but it still doesn't work.
Here is the controller to insert a comment:
public function newComment(Request $request)
{
try {
$date_format = date('Y-m-d');
$comment=new Comment();
$comment->user_id=Auth::user()->id;
$comment->introduce=$request->introduce;
$comment->completed_day=$request->completed_day;
$comment->allowance=str_replace( ',', '', $request->allowance);
$comment->post_at=$date_format;
$comment->job_id=$request->job_id;
$comment->save();
return response()->json(array('mess'=>'Success'));
}
catch (Exception $ex) {
return response()->json(array('err'=>'Error'));
}
}
Here is the view and {{$jobReply -> user -> full_name }} im using ORM to get user name
<div class="panel-body" id="job_comment_post" style="text-align:left">
<table class="table table-hover">
<thead>
<tr>
<th>Freelancer name</th>
<th>Introduce</th>
<th>Completed day</th>
<th>Allowance</th>
</tr>
</thead>
<tbody>
#foreach($job_comment as $jobReply)
<tr>
<td>{{$jobReply -> user -> full_name }}</td>
<td>{{$jobReply -> introduce}}</td>
<td>{{$jobReply -> completed_day}}</td>
<td>{{number_format($jobReply -> allowance)}}</td>
</tr>
#endforeach()
</tbody>
</table>
<div class="details_pagi">
{!! $job_comment->render() !!}
</div>
</div>
This is AJAX to insert comment:
$(document).ready(function() {
$('#btnInsertComment').click(function(event) {
event.preventDefault();
var data=$("#commentForm").serialize();
$.ajax({
url: '/postComment',
type: 'POST',
data: data,
success:function(data) {
alert(data.mess);
//job_comment_post is the div i want to load new comment
$("#job_comment_post").load();
$("#commentForm")[0].reset();
},
error:function(data) {
alert(data.err);
}
});
});
});