I am trying to use jquery datatables to output some data from a mysql database.
Here is my route:
Route::get('datatables', ['as' => 'HomeController', 'uses' => 'HomeController#getIndex']);
Route::get('payments-data', ['as' => 'HomeControllerPaymentsData', 'uses' => 'HomeController#Payments']);
My controller HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Carbon\Carbon;
class HomeController extends Controller
{
public function getIndex()
{
return view('payments');
}
/**
* Process datatables ajax request.
*
* #return \Illuminate\Http\JsonResponse
*/
public function Payments()
{
return Datatables::of(DB::table('Payment'))->make(true);
}
Here is my blade/view:
#extends('layouts.master')
#section('content')
<div class="table-responsive">
<table class="table table-hover" id="payments-table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
</table>
</div>
</div>
#push('scripts')
<script>
$(function() {
$('#payments-table').DataTable({
processing: true,
serverSide: true,
scrollX: true,
ajax: '{!! route('payments-data') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'amount', name: 'amount' },
]
});
});
</script>
#endpush
#endsection
However, when I try to run the route /datatables I get Route [payments-data] not defined. (View: /home/bob/Desktop/dibon/resources/views/payments.blade.php) What could be doing wrong? Anyone.
Use {!! route('HomeControllerPaymentsData') !!} as defined in Route::get('payments-data', ['as' => 'HomeControllerPaymentsData', 'uses' => 'HomeController#Payments']);.
Related
I'm getting an error when trying to setup a datatables with my laravel project.
DataTables warning: table id=DataTables_Table_0 - Ajax error. For more information about this error, please see http://datatables.net/tn/7
This is my controller.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Transaction;
use DataTables;
use Illuminate\Support\Facades\DB;
class TestTableController extends Controller
{
public function index()
{
return view('testtable');
}
public function getTestTable(Request $request)
{
if ($request->ajax()) {
$data = DB::table('transactions')->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$actionBtn = 'Edit Delete';
return $actionBtn;
})
->rawColumns(['action'])
->make(true);
}
}
}
This my route.
Route::get('testtable', [TestTableController::class, 'index']);
Route::get('testtable/list', [TestTableController::class, 'getTestTable'])->name('testtable.list');
View/blade.
<body>
<div class="container mt-5">
<h2 class="mb-4">Laravel 7|8 Yajra Datatables Example</h2>
<table class="table table-bordered yajra-datatable">
<thead>
<tr>
<th>ID</th>
<th>Amount</th>
<th>Charge</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js">
</script>
<script src="https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js">
</script>
<script type="text/javascript">
$(function () {
var table = $('.yajra-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('testtable.list') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'amount', name: 'amount'},
{data: 'charge', name: 'charge'},
{
data: 'action',
name: 'action',
orderable: true,
searchable: true
},
]
});
});
</script>
This is the error from laravel debugbar.
But the query did have results.
This is the output if I echo the query.
$data = DB::table('transactions')->get();
echo $data;
Anything else I'm missing? The exact same code is working if I tested in a new fresh laravel installation. This is an existing project that I try to implement datatables. I guess there must be something from current project configuration that causing the issue.
Your code in getTestTable function look fine. You got in the debugbar:
No query results for model [App\Frontend] testtable
But the code in getTestTable has nothing related to testtable so I guess route('testtable.list') doesn't get to that function. And the reason may be because you put a route like Route::get('testtable/{id}',... before Route::get('testtable/list', so when you call testtable/list, it will take list as id and go to other function.
If my guess is true, you can fix it by putting testtable/list before testtable/{id} route.
I share full details with Sample Code from my Project, this below Example code is a Manage Role DataTable from my project. please refer step by step & try to understand it.
first of all you need to install Laravel Yajra DataTable using below Composer command
composer require yajra/laravel-datatables-oracle
then after Define Routes in web.php as like my sample code
Route::get('/', [\App\Http\Controllers\Admin\RoleController::class, 'index'])->name('admin.roles.index'); //index all the data view...
Route::post('/', [\App\Http\Controllers\Admin\RoleController::class, 'getIndexUsers'])->name('admin.roles.getIndexRoles'); //Get Users for Laravel Yajra Datatable Index Page record...
then after create view file for it, I share sample from my project
<div class="card-body">
<table id="role_table" class="table table-bordered table-striped w-100">
<thead>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>No.</th>
<th>Role Name</th>
<th>Role Slug</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
<!-- /.card-body -->
& in Footer Script define Function for Initialize the DataTable like below,
<script type="text/javascript">
var dataTable = $('#role_table').DataTable({
lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
processing: true,
serverSide: true,
order: [],
searchDelay: 500,
"scrollX": "auto",
"responsive": true,
// "lengthChange": false,
"autoWidth": true,
ajax: {
url: '{{ route("admin.roles.getIndexRoles")}}',
type: 'post',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (data) {
// data.fromValues = $("#filterUserType").serialize();
},
},
columns: [
{data: 'SrNo', //try with data: 'SrNo' OR data: 'id',
render: function (data, type, row, meta) {
// return meta.row + meta.settings._iDisplayStart + 1;
return meta.row + 1;
}, searchable: false, sortable: false
},
{data: 'role_name', name: 'role_name'},
{data: 'role_slug', name: 'role_slug'},
{data: 'action', name: 'action', searchable: false, sortable: false},
],
});
</script>
then after In your Controller load Yajra DataTable Class for use it
use Yajra\DataTables\DataTables; //for Laravel DataTable JS...
Now, create Function for Display View File like this,
public function index()
{
return view('admin.roles.index');
}
Now I crated Function method for Ajax Request for DataTable Initialize
public function getIndexUsers(Request $request)
{
$roles = Role::select('roles.*');
if($request->order ==null){
$roles->orderBy('id', 'desc');
}
$detail_data = $roles;
return Datatables::of($detail_data)
->addColumn('action', function ($data) {
return $this->DataTableAction($data);
})
->rawColumns(['action'])
->make(true);
}
public function DataTableAction($data){
$btn = '<div class="btn-group">';
if($data->id == "1" || $data->id == "2"){
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" disabled>Action
</button>';
}else{
$btn .= '<button type="button" class="btn btn-danger dropdown-toggle ml-2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action
</button>';
}
$btn .= '<div class="dropdown-menu">';
$btn .= '<a class="dropdown-item" href="'.route('admin.roles.edit',$data->id).'" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-edit text-primary"></i> Edit</a>';
$btn .= '<div class="dropdown-divider"></div>';
$btn .= '<a role_id="'.$data->id.'" class="dropdown-item deleteRole" href="#" style="color: black;" onmouseover=\'this.style.background="#dee2e6"\' onmouseout=\'this.style.background="none"\'><i class="far fa-trash-alt text-danger"></i> Delete</a>';
$btn .= '</div>
</div>';
return $btn;
}
Important Note:- Currently I use Laravel 8 So, It's not necessary to needs to define Yajra Service Provider Class in config/app.php . But if you are getting any error in your different Laravel version then you wil needs to define Yajra Service Provider Class in config/app.php... for define it follow below steps
**
Note that, below step not compulsory, its depends on your Laravel
version
**
config/app.php
.....
'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
then Run below Command
php artisan optimize
then if you get any problem, try to Clear Cache using
php artisan cache:clear
Important Note:- If you define Service Provider Class in config/app.php & run optimize command, then May be Laravel will load it in autoload which is automatically called when your code references a class or interface that hasn't been loaded yet, I'm not sure
if everything is ok in the app codes,
you may loosed config for yajra..
so to configure it, you can go to the config folder in the app root directory and then open app.php file from there and add this line to the provider..
Yajra\DataTables\DataTablesServiceProvider::class
the result will be something like this:
'providers' => [
..
..
..
Yajra\DataTables\DataTablesServiceProvider::class,
]
and also add this line to the aliases:
Yajra\DataTables\Facades\DataTables::class
try like this:
'aliases' => [
..
..
..
..
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
finally, save the file(config\app.php) like above and then open up cmd or terminal and try to clear the app cached file(that includes the config cache) using the fallowing command:
php artisan optimize
Is any possible way, to add yajra datatables to existing project?
If I implement it to blank view.blade.php it works good, but if I put it to my existing project it only show thead.
My controller:
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Yajra\DataTables\DataTables;
class UserRecordController extends Controller
{
public function __construct()
{
$this->middleware(['role:admin']);
}
public function show()
{
$data = User::all()->all();
return view('management.admin-only.users.users_record')->with('data', $data);
}
public function index(Request $request)
{
if ($request->ajax()) {
$data = User::all()->all();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('management.admin-only.users.users_record');
}
}
My view:
#extends('layouts.app')
#section('content')
<div class="row admin-panel">
#include('management.common.admin_sidebar')
<div class="col" id="main">
<div class="card panel-stats">
<div class="card-body">
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div>
<div class="card-title">
<div class="card-body">
<div class="card-body">
<h2><img class="py-2 mr-3" height="100px" width="auto" src="{{ asset('img/admin/group.jpg') }}">Users</h2>
</div>
Add user
Edit user
Delete user
</div>
<div class="card-body">
<div class="card">
<table class="table table-responsive-md table-striped table-hover data-table" id="users-table">
<thead>
<tr>
<th>#</th>
<th>Firstname</th>
<th>Lastname</th>
<th>E-mail</th>
<th>Add date</th>
<th>Option</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(function () {
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('users_record') }}",
columns: [
{data: 'id', name: 'id'},
{data: 'firstname', name: 'firstname'},
{data: 'surname', name: 'surname'},
{data: 'email', name: 'email'},
{data: 'created_at', name: 'created_at'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
});
function changeUrl(el){
let urlEdit = '{{Route("users_edit_form", ":id" )}}';
urlEdit = urlEdit.replace(':id', el.value);
let urlDelete = '{{Route("users_delete_form", ":id" )}}';
urlDelete = urlDelete.replace(':id', el.value);
document.getElementById('user-edit').href = urlEdit;
document.getElementById('user-delete').href = urlDelete;
}
function checkIfChecked(){
if(document.getElementById('id-selected').checked)
{
console.log(document.getElementById('id-selected').value);
return true
}
else
{
console.log(document.getElementById('id-selected').value);
alert('Choose user to edit/delete!');
return false
}
}
function confirmation(){
let message = confirm("Are you sure?");
if(message)
return true;
else
return false;
}
</script>
#endsection
My routes:
Route::get('/admin_panel/users_record','UserRecordController#index')->name('users_record');
I worked with multiple tutorials - every looked similar. I've just imported all the neccessary webpacks to app.blade.php.
What I've done wrong?
you need two function, one is for load view like
public function index(){
return view('management.admin-only.users.users_record');
}
and another function to get data like
public function get_users_record(Request $request){
if ($request->ajax()) {
$data = User::all()->all();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'View';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
}
route will be
Route::get('/admin_panel/users_record','UserRecordController#index')->name('users_record');
Route::get('/admin_panel/get_users_record','UserRecordController#get_users_record')->name('get_users_record');
and ajax url should be
ajax: "{{ route('get_users_record') }}",
I'm looking for solution to use dropzoneJs in laravel 5.5 while writing my products.
What I want to do is: upload my images and fill my product info then save all together just like WordPress/Joomla etc.
What do I have so far:
Images Table
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('image');
$table->integer('product_id')->nullable()->unsigned();
$table->timestamps();
});
Schema::table('images', function($table) {
$table->foreign('product_id')->references('id')->on('products');
});
}
My form in Products create.blade.php
<div class="row">
<div class="col-md-12">
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone', 'id' => 'image-upload' ]) !!}
{{ csrf_field() }}
<div>
<h4 style="text-align: center;color:#428bca;">Drop images in this area <span class="glyphicon glyphicon-hand-down"></span></h4>
<!-- Input code below Not working yet -->
<input type="text" name="product_id" value="" hidden>
</div>
{!! Form::close() !!}
</div>
</div>
My JavaScript code:
<!-- drozone -->
<script type="text/javascript">
Dropzone.options.imageUpload = {
maxFilesize: 5, //MB
acceptedFiles: ".jpeg,.jpg,.png,.gif"
};
</script>
My ImageController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Image;
use App\Product;
class ImageController extends Controller
{
public function dropzone()
{
return view('dropzone-view');
}
public function dropzoneStore(Request $request)
{
$image = $request->file('file');
$imageName = time().$image->getClientOriginalName();
$image->move(public_path('images'),$imageName);
return response()->json(['success'=>$imageName]);
}
}
And my routes:
Route::get('dropzone', 'ImageController#dropzone');
Route::post('dropzone/store', ['as'=>'dropzone.store','uses'=>'ImageController#dropzoneStore']);
Any Idea On That?
I was trying to implement a searchable function using Searchable, a search trait for Laravel by nicolaslopezj, i have used the following code. But it doesn't seem to work. If there are only two records in the database it show the records but if more then two records it doesn't search.
Model: Contact.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Nicolaslopezj\Searchable\SearchableTrait;
class Contact extends Model
{
use SearchableTrait;
protected $searchable = [
'columns' => [
'contacts.first_name' => 10,
'contacts.last_name' => 10,
]];
}
Controller: SearchController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Nicolaslopezj\Searchable\SearchableTrait;
use View;
use App\Contact;
use App\Tag;
use App\Project;
use App\User;
//use Illuminate\Support\Facades\Input;
class SearchController extends Controller
{
public function findContact(Request $request)
{
return Contact::search($request->get('cname'))->get();
}
public function contactPrefetch()
{
$all_contacts= Contact::All();
return \Response::json($all_contacts);
}
}
View: show.blade.php
<script src="{{asset('global/js/plugins/datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('global/js/pages/base_tables_datatables.js')}}"></script>
<div class="input-group input-medium " style="float: right; padding-top: 3px; ">
<input type="search" name="cname" class="form-control search-input" placeholder="search contact" autocomplete="off" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap JS -->
<!-- Typeahead.js Bundle -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<script>
jQuery(document).ready(function($) {
// Set the Options for "Bloodhound" suggestion engine
var engine = new Bloodhound({
prefetch: '/find_contact_all',
remote: {
url: '/find_contact?q=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('cname'),
// queryTokenizer: Bloodhound.tokenizers.whitespace
});
$(".search-input").typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
source: engine.ttAdapter(),
name: 'contact',
display: function(data) {
return data.first_name + ' '+ data.last_name ;
},
templates: {
empty: [
'<a class="list-group-item"> Agent not found.</a>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function (data) {
return '' + data.first_name + ' ' + data.first_name + ''
}
}
});
});
</script>
Routes:
Route::get('find_contact', 'SearchController#findContact');
Route::get('find_contact_all', 'SearchController#contactPrefetch');
Simply add the package to your "composer.json" file and "composer update"[update your composer]
"nicolaslopezj/searchable": "1.*"
I have added this package https://github.com/yajra/laravel-datatables into my package and i am trying to use it in my application.
This is the view
#section('content')
<table class="table table-bordered" id="users-table">
<thead>
<tr>
<th>Emp No</th>
<th>Birth Date</th>
<th>First Name</th>
<th>Last Name</th>
<th>Gender</th>
<th>Hire Date</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script type="text/javascript">
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
responsive: true,
ajax: 'http://localhost:8000/tasks',
columns: [
{ data: 'emp_no', name: 'emp_no' }
{ data: 'birth_date', name: 'birth_date' },
{ data: 'first_name', name: 'first_name' },
{ data: 'last_name', name: 'last_name' },
{ data: 'gender', name: 'gender' },
{ data: 'hire_date', name: 'hire_date' }
]
});
});
</script>
#endpush
#endsection
This is the route
Route::get('tasks', 'PrototypeController#getTasks')->name('datatable.tasks');
This is the controller
public function getTasks()
{
return Datatables::of(Employees::query())->make(true);
//returns json
}
This code loads the view containining the datatables.
The url http://localhost:8000/tasks returns the json in the web browser but the datatable is never rendered in my view. When i check in my view, there are no browser errors.
What could be the problem?.
Create two method, one display our view and other method that will process our datatables ajax request.
Display our view
public function viewTasks()
{
return view('Tasks.index');
}
Process our datatables ajax request
public function getTasks()
{
return Datatables::of(Employees::query())->make(true);
}
Reference Link :- Yajra Datatable
You should change in your controller. Add code below for showing data table:
public function task()
{
return view('datatables.Index');
}
Change in web.php file for add new route:
Route::get( 'employee','PrototypeController#task');
Add data table CDN and bootstrap also
<link href="https://datatables.yajrabox.com/css/app.css" rel="stylesheet">
<link href="https://datatables.yajrabox.com/css/datatables.bootstrap.css" rel="stylesheet">
<link href='https://fonts.googleapis.com/css?family=Lato:400,700,300|Open+Sans:400,600,700,800' rel='stylesheet'
type='text/css'>