How to display my JSON response in a table using Laravel? - php

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);

Related

How to delete file in my database Laravel

How do I delete files in the database, because when I click delete the data in the folder is deleted, but the data in the file_rekap tables don't want to be deleted, but the ones in the rekap table are deleted
RekapController:
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
public function files($id){
$data = rekap::find($id);
if(!$data) abort(404);
$files = $data->files;
return view ('file_rekap',compact('data','files'));
}
Model rekap and file_rekap
class rekap extends Model{
use HasFactory;
protected $fillable = [
'customer',
'vessel',
'scopejob',
'pergantian_sparepart',
'teknisi',
'tahun',
'keterangan',
];
public function files(){
return $this->hasMany(file_rekap::class);
}
}
/////////////////////////////////
class file_rekap extends Model
{
use HasFactory;
protected $fillable = [
'file',
'rekap_id',
];
public function rekaps(){
return $this->belongsTo(rekap::class);
}
}
and script in my rekap_blade
#csrf
<div class="modal-body">
<div class="form-group">
<input type="file" name="import_excel" required>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
<div class="row g-2 align-items-center m-2">
<form action="/rekap" method="GET">
<div class="input-group">
<input type="text" class="form-control " placeholder="Cari..." name="search">
<button class="btn btn-info" type="submit">Search</button>
</div>
</div>
</form>
<table class="table">
<thead class="thead ">
<tr>
<th scope="col">Customer</th>
<th scope="col">Vessel/Unit</th>
<th scope="col">Scope Job</th>
<th scope="col">Pergantian Spare Part</th>
<th scope="col">Teknisi</th>
<th scope="col">Bulan Tahun</th>
<th scope="col">Catatan</th>
<th scope="col">Total File</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
#foreach ($data as $row)
<tr>
<td>{{ $row->customer}}</td>
<td>{{ $row->vessel}}</td>
<td>{{ $row->scopejob}}</td>
<td>{{ $row->pergantian_sparepart}}</td>
<td>{{ $row->teknisi}}</td>
<td>{{ $row->tahun}}</td>
<td>{{ $row->keterangan}}</td>
<td>{{ $row->files->count()}}</td>
<td>
FILE
EDIT
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
</td>
</tr>
#endforeach
</tbody>
</table>
</tbody>
</table>
{{ $data->links() }}
</div>
</div>
</div>
#endsection
<script>
$('.delete').click(function(){
var rekapid = $(this).attr('data-id');
var customer = $(this).attr('data-customer');
swal({
title: "Yakin",
text: "Kamu akan menghapus data dengan nama "+customer+" ",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location = "/delete_rekap/"+rekapid+" "
swal("Data Berhasil Terhapus", {
icon: "success",
});
} else {
swal("File Anda Aman");
}
});
});
</script>
How ti fix it ?
If you want to work with other developers in the future, make sure to work to common coding standards, such as using upper camel case for classes. Also consider the correct indentation.
Anyway, you don't actually delete the database record when deleting files
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file) {
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
$file->delete();
}
This isn't the optimum case as a database query is executed for every loop over the files collection.
Better is to perform a separate delete
public function delete_rekap($id){
$data = rekap::findOrfail($id);
$files = file_rekap::where("rekap_id", $data->id)->get();
foreach($files as $file){
if (File::exists("rekap_file/".$file->file)) {
File::delete("rekap_file/".$file->file);
}
}
file_rekap::where("rekap_id", $data->id)->delete();
$data->delete();
return redirect()->route('rekap')->with('success','Data berhasil dihapus');
}
if you have a relationship set up, you can also delete via that
$data->file_recap()->delete();
make sure your data is not important when experimenting with delete
$status=unlink('data.txt');
// Delete a single file
File::delete($filename);

I am getting 500 Internal Error when trying to pass named route with two parameter in my controller

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.

Changing roles on admin panel in checkbox

In presented controller, it's displaying all the users and his attributes(?) such as name, surname, phone and roles. How do I make it that when I select role in checkbox and press "potvrdi"(submit) it submits to database? Do I have to use jquery, ajax?
Thank you
Controller
public function action(Request $request)
{
if ($request->ajax()) {
$query = $request->get('query');
if ($query != '') {
$data = User::where('surname', 'like', '%'.$query.'%')
->orWhere('name', 'like', '%'.$query.'%')
->orWhere('phone', 'like', '%'.$query.'%')
->orderBy('id')
->get();
} else {
$data = User::orderBy('id')
->get();
}
return json_encode($this->generateUserTable($data));
}
}
public function generateUserTable($data)
{
$total_row = $data->count();
$output = "";
if ($total_row > 0) {
foreach ($data as $row) {
$roleNames = '';
$userRoles = $row->roles()->pluck('id')->toArray();
// var_dump($userRoles);
$checked = '';
foreach (Role::all() as $roles1) {
if (in_array($roles1->id, $userRoles)) {
$checked = 'checked="checked"';
}
$roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
}
$output .= '
<tr>
<td>'.$row->surname.'</td>
<td>'.$row->name.'</td>
<td>'.$row->phone.'</td>
<td>'.$roleNames.'</td>
<td><button type="button" id="potvrdi" class="potvrdi-button btn btn-primary" data-id="'.$row->id.'">
<div class="potvrdi">Potvrdi</div>
</button></td>
<td><button type="button" id="rowId" class="remove-button btn btn-danger" data-id="'.$row->id.'">
<div class="close">x</div>
</button></td>
</tr>
';
}
} else {
$output = '
<tr>
<td align="center" colspan="5">Nema podataka</td>
</tr>
';
}
return array(
'table_data' => $output,
'total_data' => $total_row,
);
}
EDIT:
part of html is in controller after $output in generateUserTable
view with js
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<h2>{{ $modal }}</h2>
</div>
<div class="modal-footer">
<button type="button" class="rem-mod btn btn-secondary" data-dismiss="modal">Zatvori</button>
<button type="button" class="bck-mod test btn btn-danger" data-dismiss="modal">Obriši korisnika</button>
</div>
</div>
</div>
</div>
<!-- users and search bar -->
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Pretraži korisnike</div>
<div class="panel-body">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Pretraži korisnike" />
</div>
<div class="table-responsive">
<h3 align="center">Broj korisnika: <span id="total_records"></span></h3>
<table id="users" class="table table-striped table-bordered">
<thead>
<tr>
<th>Prezime</th>
<th>Ime</th>
<th>Telefon</th>
<th>Rola</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
Gets data from database
<script>
$(document).ready(function(){
fetch_user_data();
function fetch_user_data(query = ''){
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('click', '.potvrdi-button', function(){
post_user_role();
var id = $(this).data('id');
function post_user_role(id){
$.ajax({
url:"{{ route('live_search.action') }}",
method:"GET",
data:{id:id},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
})
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_user_data(query);
});
Modal js
$('#users').on('click', '.remove-button', function(){
var id = $(this).data('id');
$(".test").attr('data-id', id);
$("#deleteModal").modal("show");
});
$(document).on('click', '.bck-mod', function(){
var id = $(this).data('id');
$.ajax({
//url:"{{ route('live_search.destroy') }}",
url:"/live_search/destroy",
method:"get",
data:{id:id},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
},
error: function(data)
{
console.log(data);
}
})
});
});
</script>
I prepared sample fiddle for you. I used dummy values for your users table, also I used select instead of checkbox, but you should follow the same approach.
$(document).on('click', '.potvrdi-button', function(e) {
var value = $(this).closest('tr').find('select[name="role"]').val();
$.ajax({
url: "{{ route('live_search.action') }}",
method: "GET",
data: {
value: value
},
dataType: 'json',
success: function(data) {
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
})
Check your method. Right now it's a GET. You probably want it to be a POST. Check your laravel router to make sure its responding to the POST method.

Laravel datatable. Illegal string offset 'start'

I have a datatable that works great. However, on the last column I have a button which should do another query and then build a second datatable, based on these results.
As you can see on the following example, when I click on the button 'searchMom' in the first row, it should run a query based on john newman´s mother('mary newman') and put the results on the panel called "Mom".
But it´s not working.
Please see the image and the code below:
View: viewFamily.blade.php
<div class="row">
<div class="col-md-12" id="rowFamily01">
<div class="panel">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
</div>
<div class="panel-title">Find a person</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-9">
<div class="form-group">
<label class="control-label" for="inputPersonSearch" >Search: </label>
<input id="inputPersonSearch" class="form-control" type="text" name="inputPersonSearch" form="formPerson">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label" for="btnPersonSearch" style="color: white;">Search:</label>
<button id="btnPersonSearch" class="form-control btn btn-success" type="submit" title="Search" form="formPerson">Search</button>
</div>
</div>
</div>
<div class="row" style="width:100%; margin-left: 0%;">
<div class="col-md-12 datatable" id="datatable-main">
</div>
</div>
</div>
</div>
</div>
</div>
routes: diego_routes.php
Route::group(['prefix' => 'diego', 'namespace' => 'Diego'], function () {
Route::get("/", "DiegoController#index")->name("index");
Route::get("viewFamily", "DiegoController#viewFamily")->name("viewFamily");
Route::post("searchPerson", "DiegoController#searchPerson")->name("searchPerson");
Route::get("searchMom/{mom}", "DiegoController#searchMom")->name("searchMom");
});
controller: DiegoController.php
public function searchMom($mom){
$input = $mom;
//dd($input);
//begining select query
$query = TD_CP_CIDADAO::where('CID_INT_ID_CIDADAO', '>=', "0");
if(!empty($input["filtro"])){
foreach($input["filtro"] as $k=>$v){
if(!empty($k) and !empty($v)){
//$searchValues = preg_split('/,/', $v, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = array_map('trim', $v);
//dd($searchValues);
$query->where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('CID_STR_DS_NOME', 'like', "%{$value}%");
}
});
}
}
}
//order data
if(!empty($input["order"]) and count($input["order"]) > 0)
{
foreach($input["order"] as $v){
$position = $v["column"];
$column = $input["columns"][$position]["data"];
$dir = !empty($v["dir"])? $v["dir"] : "asc";
$query->orderBy($column, $dir);
}
}
//other params...
$query->skip($input["start"])->take($input["length"]);
$json_data["data"] = $query->get()->toArray();
$json_data["recordsTotal"] = $query->count();
$json_data["recordsFiltered"] = $json_data["recordsTotal"];
$json_data["draw"] = $input["draw"];
return response()->json($json_data);
}
javascript: diego.js
$(document).on("click", ".btnMom", function(e){
e.preventDefault();
$("#newPanels").empty();
$("#newPanels").append(panelMom);
$("#datatable-mom").append(tableMom);
$("#datatable-mom").css("font-size", "12px");
if($.fn.dataTable.isDataTable('table#tbMom')){
$("table#tbMom").DataTable().destroy();
}
$.fn.dataTable.ext.errMode = 'throw';
var filtros = $(this).serializeArray().reduce(function(a, x) { a[x.name] = x.value; return a; }, {});
var options = {
serverSide: true,
processing: true,
retrieve: true,
ajax: {
dataSrc: 'data',
url : $(this).data("url"),
type: 'get',
async: false,
data: {filtro:filtros}
},
columns : columnsMom,
lengthMenu : [ 5, 10, 25 ]
};
$("table#tbMom").DataTable(options);
});
var columnsMom = [
{ data: 'CID_INT_ID_CIDADAO', visible:false},
{ data: 'CID_STR_DS_NOME'},
{ data: 'CID_DAT_DT_NASCIMENTO',
render: function(data, type, row){
return converterData(data);
}, className: "text-center"},
{ data: 'CID_STR_NM_MAE'},
{ data: 'CID_STR_NM_PAI'},
{ data: 'CID_INT_NR_RG', className: "text-center"},
{ data: 'CID_INT_NR_CPF', className: "text-center"},
{ data: 'acao',
render: function(data, type, row, meta){
var b0 = '\n\
\n\
';
return b0;
},orderable: false, className: "text-center"
}];
var panelMom =
`
<div class="panel" id="panelMom">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
<button type="button" class="btn btn-xs panel_remove"><i class="material-icons md-18">close</i></button>
</div>
<div class="panel-title">Mom</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 datatable conteudod" id="datatable-mom">
</div>
</div>
</div>
</div>
`;
var tableMom =
`
<table id="tbMom" class="table table-hover compact" cellspacing="0" width="100%" >
<thead>
<tr>
<th class="hidden">ID</th>
<th>NAME</th>
<th>DOB</th>
<th>MOM</th>
<th>DAD</th>
<th class="text-center">DOC #</th>
<th class="text-center">FIELD #</th>
<th class="text-center">ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
`;
The error message:
The line 219 (controller) shown in error message:
Results on "dd($input)" inside the controller:
I appreciate any help to solve this problem!
Thank you!
You're setting the value of $input to the value of $mom, which is the last value in your URL, so mom equals Mary Newman but the rest of your code expects $input to be an array of parameters like order, columns and start.
You should assign the value of $input as the request parameters, e.g:
public function searchMom($mom)
{
$input = request()->input();
}
Alternatively instead of $input being an array you could use the Request object directly, e.g:
public function searchMom(Request $request, $mom)
{
$request->order;
$request->columns;
$request->start;
}

X-Editable table in laravel using blade

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

Categories