Error 405: Method not allowed, EditUser route can't get info - laravel

So I've been learning Laravel and was getting into making DataTables. However, my 'editItem' route is not being able to get any information when I click 'Edit' button. It shows Error 405.
DataTable view (dt.blade.php) -
HTML part where the table is displayed
<div class="table-responsive text-center">
<table class="table table-borderless" id="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">Name</th>
<th class="text-center">Created At</th>
<th class="text-center">Updated At</th>
<th class="text-center">Actions</th>
</tr>
</thead>
#foreach($users as $user)
<tr class="user{{$user->id}}">
<td >{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->created_at}}</td>
<td>{{$user->updated_at}}</td>
<td><button class="edit-modal btn btn-info"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-edit"></span> Edit
</button>
<button class="delete-modal btn btn-danger"
value="{{$user->id}},{{$user->name}}">
<span class="glyphicon glyphicon-trash"></span> Delete
</button></td>
</tr>
#endforeach
</table>
</div>
JS part in the same file
<script>
$(document).ready(function() {
$('#table').DataTable();
} );
</script>
<script>
$(document).on('click', '.edit-modal', function() {
$('#footer_action_button').text("Update");
$('#footer_action_button').addClass('glyphicon-check');
$('#footer_action_button').removeClass('glyphicon-trash');
$('.actionBtn').addClass('btn-success');
$('.actionBtn').removeClass('btn-danger');
$('.actionBtn').removeClass('delete');
$('.actionBtn').addClass('edit');
$('.modal-title').text('Edit');
$('.deleteContent').hide();
$('.form-horizontal').show();
var stuff = $(this).val().split(',');
console.log($(this).val());
fillmodaluser(stuff)
$('#myModal').modal('show');
});
$(document).on('click', '.delete-modal', function() {
$('#footer_action_button').text(" Delete");
$('#footer_action_button').removeClass('glyphicon-check');
$('#footer_action_button').addClass('glyphicon-trash');
$('.actionBtn').removeClass('btn-success');
$('.actionBtn').addClass('btn-danger');
$('.actionBtn').removeClass('edit');
$('.actionBtn').addClass('delete');
$('.modal-title').text('Delete');
$('.deleteContent').show();
$('.form-horizontal').hide();
var stuff = $(this).val().split(',');
console.log($(this).val('info'));
$('.did').text(stuff[0]);
$('.dname').html(stuff[1]);
$('#myModal').modal('show');
});
function fillmodaluser(details){
$('#fid').val(details[0]);
$('#name').val(details[1]);
}
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'post',
url: '../public/editUser',
user: {
'_token': $('input[name=_token]').val(),
'id': $('#fid').val(),
'name': $('#name').val()
},
success: function(user) {
if (user.errors){
$('#myModal').modal('show');
if(user.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("Name can't be empty !");
}
if(user.errors.email) {
$('.email_error').removeClass('hidden');
$('.email_error').text("Email must be a valid one !");
}
}
else {
$('.error').addClass('hidden');
$('.user' + users.id).replaceWith("<tr class='users" + users.id + "'><td>" +users.id + "</td><td>" + users.name+"</td><td>" + "</td><td>" + "</td><td><button class='edit-modal btn btn-info' user-info='" + users.id+","+users.name+"'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' user-info='" + users.id+","+users.name+"' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
}}
});
});
$('.modal-footer').on('click', '.delete', function() {
$.ajax({
type: 'post',
url: '../public/deleteUser',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
user: {
'_token': $('input[name=_token]').val(),
'id': $('.did').text()
},
success: function(user) {
$('.user' + $('.did').text()).remove();
}
});
});
</script>
And lastly, the web.php
Route::get('/dt', 'UserController#dt');
Route::get('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::get ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});
The JSON error that shows to me is "{"errors":{"name":["The name field is required."]}}"
My question is that, the info can be split fine in the JQuery here when I press the Edit button; it is able to show the info of the row I've selected. I don't understand why the same values aren't getting sent to my editUser route?

change all get method to post , because you are using post in client side
Route::post('/dt', 'UserController#dt');
Route::post('/editUser', function (Request $request) {
$rules = array (
'name' => 'required|alpha',
);
$validator = Validator::make(Input::all(), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag()->toArray ()
) );
else {
$user->id = User::find ( $request->id );
$user->name = ($request->name);
$user->save ();
return response ()->json ( $user );
}
});
Route::post ('/deleteUser', function (Request $request) {
User::find ( $request->id )->delete ();
return response ()->json ();
});

Seems your urls should not be '../public/' (in your ajax requests) but it should match what you typed in your file web.php

Related

Anyone can tell me whats wrong in here when im putting a array of number like :1,2 its starting to freeze the screen i hope someone can help me thanks

Hello guys im trying to learn vue and im trying to use datatable from https://datatables.net/ and having a problem with my action button that im not able to get the id when the #viewModal is been triggered i hope someone can help me to get the id of each buttons thanks and here is my code TIA:
EmployeeDataTable Component :
<template>
<div class="card">
<div class="card-header">
<div class="card-title">Employee List</div>
</div>
<div class="card-body">
<div class="table-responsive">
<table
id="employee-table"
class="table-sm table-bordered table-hover text-center display"
width="100%"
>
<thead>
<tr>
<th class="pt-3 pb-3">#</th>
<th>Name</th>
<th>Address</th>
<th>Contact #</th>
<th>Department</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
</template>
<script>
//For Datatable to work
import "datatables.net";
import EmployeeEdit from "./EmployeeEdit.vue";
export default {
name: "EmployeeList",
data() {
return {
employees: [],
};
},
mounted() {
this.getEmployeeLists();
},
components: {
"employee-edit": EmployeeEdit,
},
methods: {
getEmployeeLists() {
// INITIALIZE DATATABLE
$("#employee-table")
.DataTable({
//LOADING
// processing: true,
//AJAX
serverSide: true,
//DIRECTION
order: [[1, "desc"]],
//AJAX
ajax: {
url: "/api/getEmployeeLists",
dataList: "json",
type: "POST",
data: { _token: "{{csrf_token()}}" },
},
//TABLE COLUMNS SHOULD BE THE SAME IN CONTROLLER
columns: [
{ data: "#" },
{ data: "name" },
{ data: "address" },
{ data: "contact" },
{ data: "department" },
{ data: "status" },
{
data: "actions",
//allowing modification
createdCell(cell, cellData, rowData) {
let EmployeeListDataTableActions = Vue.extend(
require("./EmployeeListDataTableAction.vue").default
);
let instance = new EmployeeListDataTableActions().$mount();
$(cell).empty().append(instance.$el);
},
},
],
//View Count in Table
lengthMenu: [
[10, 25, 50, -1],
[10, 25, 50, "All"],
],
})
.columns();
},
beforeDestroy: function () {
$(this.$el).DataTable().destroy();
},
},
};
</script>
EmployeeDataTableAction Component :
<template>
<button class="btn btn-primary btn-sm" #click="viewModal" title="View Employee Details">
<i class="fa fa-eye"></i>
</button>
</template>
<script>
export default{
name: 'EmployeeListDataTableAction',
data: function() {
return {
}
},
mounted() {
},
methods: {
viewModal() {
var id = $(this.$el).closest('tr').find('input').val();
return false;
axios
.post(`/api/getEmployeeDetails/${id}`, {
id: id,
})
.then((response) => {
$("#edit-employee-modal").modal("show");
$(".myModalLabel").text(
response.data.name +
" - " +
response.data.department_name
);
state.commit("getEmployeeDetailsArray", response.data);
state.commit("getTransactionId", response.data.id);
})
.catch((response) => {
this.$toast.top("Something went wrong!");
});
},
},
}
</script>
Employee Controller for the DataTable :
public function employeeList(Request $request){
$all = Employee::getEmployeeTotal();
//total count of data
$total_data = $all;
//total filter
$total_filtered = $total_data;
//set_time_limit(seconds)
$limit = $request->input('length');
//start
$start = $request->input('start');
//order
// $order = $columns[$request->input('order.0.column')];
//direction
$dir = $request->input('order.0.dir');
$search_value = $request->input('search.value');
if (!empty($search_value)) {
$posts = Employee::getEmployeeNameSearch($search_value,$start, $limit, $dir);
$total_data = count($posts);
$total_filtered = $total_data;
}else{
if(empty($request->input('search.value')))
{
//if no search
$posts = Employee::getEmployeeList($start, $limit, $dir);
}
}
$data = array();
if(!empty($posts))
{
$counter = $start + 1;
foreach ($posts as $post)
{
$department = GlobalModel::getSingleDataTable('departments',$post->department_id);
$status = StatusController::checkStatus($post->status);
$nested_data['#'] = '<span style="font-size: 12px ; text-align: center;">'.$counter++.'</span>';
$nested_data['name'] = '<p style="text-align: center;">'.$post->name.'</p>';
$nested_data['address'] = '<p style="text-align: center;">'.$post->address.'</p>';
$nested_data['contact'] = '<p style="text-align: center;">'.$post->contact.'</p>';
$nested_data['department'] = '<p style="text-align: center;">'.$department->name.'</p>';
$nested_data['status'] = '<p style="text-align: center;">'.$status.'</p>';
$nested_data['actions'] = '';
$data[] = $nested_data;
}
}
$json_data=array(
"draw" => intval($request->input('draw')),
"recordsTotal" => intval($total_data),
"recordsFiltered" => intval($total_filtered),
"data" => $data
);
return response()->json($json_data);
}
In the second line of your viewModal() function, you are placing a return false; statement. "The return statement ends function execution and specifies a value to be returned to the function caller." From Mozilla docs. That's why the API call is never executing.

Undefined variable when returning view as HTML via AJAX

I'm new to Laravel and I'm trying to prepend the view when adding a new category. I'm always getting the error:
Undefined variable: category (View: ..new.blade.php) ... Line 1
Here's what I have so far:
CategoryController.php
public function store(Request $request)
{
$request->validate([
'name' => 'required'
]);
$category = new Category();
$category->name = $request->name;
$category->save();
$returnHTML = view('categories.new', compact($category))->render();
return response()->json(array(
'success' => true,
'html' => $returnHTML,
'icon' => 'success',
'title' => 'Added',
'msg' => 'Category successfully added.'
));
}
script.blade.php
$('#category-submit').click( function() {
var name = $('#name').val();
let _url = '/categories';
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: _url,
type: 'POST',
data: {
name: name,
_token: _token
},
success: function(data) {
$('tbody').prepend(data.html);
$('#name').val('');
$('#category-modal').modal('hide');
Swal.fire({
title: data.title,
text: data.msg,
icon: data.icon,
showConfirmButton: false,
timer: 1500
});
},
error: function(xhr) {
console.log(xhr.responseText);
}
});
});
new.blade.php
<tr id="category-{{ $category->id }}">
<td>{{ $category->name }}</td>
<td>
<button class="btn btn-inverse-primary btn-icon-text">
<i class="ti-pencil btn-icon-prepend"></i> Edit
</button>
<button data-id="{{ $category->id }}" class="category-delete btn btn-inverse-danger btn-icon-text">
<i class="ti-trash btn-icon-prepend"></i> Delete
</button>
</td>
</tr>
I honestly don't know what I'm doing wrong. It seems $category from controller won't be passed to new.blade.php. Any help would be greatly appreciated.
As described here in php doc, you should pass the name of the variable as a string in compact() method.
$returnHTML = view('categories.new', compact('category'))->render();
Or you can pass the variable to blade file using array.
$returnHTML = view('categories.new', ['category' => $category])->render();

A dropdown in the laravel for filtering table data

I want to know something in Laravel. I want a dropdown for classes so when the user selects any class and press the submit button then the users related to that specific class will be displayed below in the table... Is it possible?
Below is the code I did for getting the data but I want this data to refer to my table in the HTML because there is something more I want and I can't add those things to the ajax table
//My ajax
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if(classID) {
$.ajax({
url: '/myform/ajax/'+classID,
type: "GET",
dataType: "json",
success:function(data) {
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td>' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name+ ' ' + value.last_name + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//Controller
public function index(Request $request){
$classes = StudentsClass::pluck('class_name', 'id')->all();
return view('admin.students.attendance.index', compact( 'classes'));
}
public function mytableAjax($id) {
$students = Student::where('students_class_id', $id)->get();
return json_encode($students);
}
//My view
<select name="students_class_id" class="form-control" style="width:350px">
<option value="">--- Select State ---</option>
#foreach ($classes as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<table id="studentsData" class="table table-striped table-bordered table-list-search">
<thead>
<tr>
<th>#</th>
<th>Student ID</th>
<th>Student Name</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<select class="form-control" id="gender">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>
</td>
</tr>
</tbody>
</table>
<a class="fas fa-folder-open btn btn-success float-right mb-4 mr-2"> Save</a>
</div>
Check the following code that will add the attendance column for every row :
$(document).ready(function() {
$('select[name="students_class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/myform/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var attendance = `<div class="form-group">
<select class="form-control" id="gender" name="attendance[]">
<option>Present</option>
<option>Absent</option>
<option>Leave</option>
</select>
</div>`;
var markup = '';
$.each(data, function(key, value) {
markup += '<tr> <td><input type="hidden" value="'+value.id+'" name="id[]">' + value.id + '</td> <td>' + value.student_id + '</td> <td>' + value.first_name + ' ' + value.last_name + '</td> <td> ' + attendance + '</td> <tr>';
});
$('#studentsData tbody').html(markup);
var thead_markup += '<tr> <th>A</th> <th>B</th> <th>C</th> <td>D</th> <tr>';
$('#studentsData thead').html(thead_markup);
}
});
}
});
});
It depends upon your code, if you are using ajax datatables api then here is a similar example:
$(document).ready(function() {
$('#example').DataTable( {
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.footer()).empty() )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
}
} );
} );
Reference: datatables.net multi filter select
If you are not using datatables api and do not want ajax then use below code and change according to your need:
$("#selectDropdown").on("change", function () {
var value = $(this).val();
$("table tr").each(function (index) {
if (index != 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) != 0) {
$(this).hide();
}
else {
$(this).show();
}
}
});
});

trying to integrate ajax autocomplete in my create record in laravel

I found a ajax auto complete and I wan't it to integrate to my form but I can't make it work. Please advise thank you!
[controller]
<?php
namespace App\Http\Controllers;
use App\Purchasetransactions;
use App\AjaxAutocompleteController;
use App\Products;
use App\Categories;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class PurchasetransactionsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$purchasetransactions = Purchasetransactions::all();
return view('orders.index', compact('purchasetransactions'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('orders.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$purchasetransactions = Purchasetransactions::create($request->only('products_code','name'));
return redirect(route('orders.index'));
}
/** Auto Complete */
public function productSearch(Request $request){
$query = $request->get('term','');
$products=\DB::table('products');
if($request->type=='product_code'){
$products->where('product_code','LIKE','%'.$query.'%');
}
if($request->type=='product_name'){
$products->where('name','LIKE','%'.$query.'%');
}
$products=$products->get();
$data=array();
foreach ($products as $product) {
$data[]=array('product_code'=>$product->product_code,'name'=>$product->name);
}
if(count($data))
return $data;
else
return ['product_code'=>'','name'=>''];
}
}
[create.blade]
<div class="container">
{!! Form::open(array('route'=>'orders.store')) !!}
<table class="table table-bordered">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>Product Code</th>
<th>product name</th>
</tr>
<tr>
<td><input type='checkbox' class='chkbox'/></td>
<td><span id='sn'>1.</span></td>
<td><input class="form-control autocomplete_txt" type='text' data-type="product_code" id='product_code_1' name='product_code[]'/></td>
<td><input class="form-control autocomplete_txt" type='text' data-type="product_name" id='product_name_1' name='product_name[]'/> </td>
</tr>
</table>
<button type="button" class='btn btn-danger delete'>- Delete</button>
<button type="button" class='btn btn-success addbtn'>+ Add More</button>
{!! Form::close() !!}
</div>
<script type="text/javascript">
$(".delete").on('click', function() {
$('.chkbox:checkbox:checked').parents("tr").remove();
$('.check_all').prop("checked", false);
updateSerialNo();
});
var i=$('table tr').length;
$(".addbtn").on('click',function(){
count=$('table tr').length;
var data="<tr><td><input type='checkbox' class='chkbox'/></td>";
data+="<td><span id='sn"+i+"'>"+count+".</span></td>";
data+="<td><input class='form-control autocomplete_txt' type='text' data-type='product_code' id='product_code_"+i+"' name='product_code[]'/></td>";
data+="<td><input class='form-control autocomplete_txt' type='text' data-type='product_name' id='product_name_"+i+"' name='product_name[]'/></td></tr>";
$('table').append(data);
i++;
});
function select_all() {
$('input[class=chkbox]:checkbox').each(function(){
if($('input[class=check_all]:checkbox:checked').length == 0){
$(this).prop("checked", false);
} else {
$(this).prop("checked", true);
}
});
}
function updateSerialNo(){
obj=$('table tr').find('span');
$.each( obj, function( key, value ) {
id=value.id;
$('#'+id).html(key+1);
});
}
//autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
type = $(this).data('type');
if(type =='product_code' )autoType='product_code';
if(type =='product_name' )autoType='name';
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.ajax({
url: "{{ route('productsearch') }}",
dataType: "json",
data: {
term : request.term,
type : type,
},
success: function(data) {
var array = $.map(data, function (item) {
return {
label: item[autoType],
value: item[autoType],
data : item
}
});
response(array)
}
});
},
select: function( event, ui ) {
var data = ui.item.data;
id_arr = $(this).attr('id');
id = id_arr.split("_");
elementId = id[id.length-1];
$('#product_code_'+elementId).val(data.product_code);
$('#product_name_'+elementId).val(data.name);
}
});
});
</script>
[route]
Route::get('/orders/create','PurchasetransactionsController#create')->name('orders.create');
Route::get('productsearch', ['as'=>'productsearch','uses'=>'PurchasetransactionsController#productsearch']);
I've added multiple autocomplete searches to input fields in laravel, and i've always had to look it back up each time i've implemented it. This is working for me. Here is the input which i'm searching for matching abbreviations in my search
<div class="input-group">
#if(isset($_GET['variable_name']))
<input value="{{$_GET['variable_name']}}" type="search" name="variable_name" class="form-control" id="variable_name" autocomplete="off">
#else
<input type="search" name="variable_name" class="form-control" id="variable_name" placeholder="Search" autocomplete="off">
#endif
</div>
Script to control ajax return:
$(document).ready(function($) {
// Set the Options for "Bloodhound" suggestion engine
var engine = new Bloodhound({
remote: {
url: '/find?variable_name=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('variable_name'),
queryTokenizer: Bloodhound.tokenizers.whitespace
});
$('#variable_name').typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
name: 'abbreviations',
source: engine,
display: function(data) {
console.log(data);
return data.abbreviation //Input value to be set when you select a suggestion.
},
templates: {
empty: [
'<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function(data) {
return '<div style="font-weight:normal; margin-top:-10px ! important;" class="list-group-item">' + data.abbreviation + ' ' + data.table + '</div></div>'
}
}
});
});
Controller function
public function find(Request $request) {
$result=Abbreviation::where('abbreviation', 'LIKE', "%{$request->input('variable_name')}%")
->orWhere('name', 'LIKE', "%{$request->input('variable_name')}%")->get();
return response()->json($result);
}
My Route:
Route::get('/find', 'PagesController#find')->name('typeahead.search');
libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Also need the bloodhound.js and tyepahead.jquery

Update paginator laravel in ajax

I create a page on which there is a table with a paginator. I post a request to specify the output of rows from the database for insertion into the table. However, the paginator remains old. How should I change it?
Get a request for a new page or insert all the HTML code that comes from the controller is not satisfied.
Code view:
<table class="table table-bordered text-center table-hover" id="table_list">
<thead>
<tr>
<th>id</th>
</tr>
<tr>
<td><input type="text" class="form-control" id="id_card" value=""></td>
</tr>
</thead>
<tbody>
#if($dats)
#foreach($dats as $data)
<tr>
<td><div class="help" data-id="{{ $data['id'] }}"> {{$data['id']}}</div></td>
</tr>
#endforeach
#endif
</tbody>
</table>
{{ $dats->links() }} // After completing the ajax, the link remains old and allows you to navigate through the old table
Js code in view:
$('#id_card').on('keyup', function(){ // search
value = $(this).val();
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}'
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data); // update table
//update paginator links
},
error: function(data){
console.log(data);
}
})
})
Code controller
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
print($str);
return;
}
In Laravel 5, you could do it by changing your controller to something like this.
public function search(Request $request){
$models= Model::where('table','LIKE','%'.$request->input('search').'%')->paginate(4);
$str = "";
foreach($models as $model){
$str .= '<tr>'.
'<td>'. $model["id"].'</td>'.
'</tr>';
}
return response()->json([
'rows' => $str,
'links' => $models->render()
], 200);
}
In your ajax response, render the links with $('ul.pagination').replaceWith(data.links);
eg.
$.ajax({
type: 'POST',
url: '/home',
data: {
search: value,
code: 1,
_token: '{{csrf_token()}}',
page: page
},
success: function (data) {
$('#table_list').empty();
$('#table_list').append(data.rows); // update table
$('ul.pagination').replaceWith(data.links); // update links
},
error: function(data){
console.log(data);
}
});

Resources