Datatable service Yajra show blank - datatable

i want to add button in Yajra, so i read http://dt54.yajrabox.com/buttons/eloquent.
Im following the step. But still show blank.
nb. if im not using datatable service running well.
Datatables class
namespace App\DataTables;
use App\employee;
use Yajra\Datatables\Services\DataTable;
class EmployeeDataTable extends DataTable
{
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->make(true);
}
public function query()
{
$query = employee::select();
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->ajax('{{ url("Employee/index3") }}')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
]);
}
protected function filename()
{
return 'employeedatatables_' . time();
}
in Controller
use Yajra\Datatables\Facades\Datatables;
use App\DataTables\EmployeeDataTable;
public function index3(EmployeeDataTable $dataTable)
{
return $dataTable->render('employee.users');
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table() !!}
</div>
{!! $dataTable->scripts() !!}
#endsection
If i used firebug, i've got error 304 not modified.
Can you tell me what my mistake,pls ?

Solved.. maybe can help somebody..
this is Column search,and add action using Datatabale service
in Datatables class
public function ajax()
{
return $this->datatables
->eloquent($this->query())
->addColumn('action', function ($query) {
return '<i class="glyphicon glyphicon-edit"></i> Edit
<i class="glyphicon glyphicon-minus-sign"></i> Del';
})
->make(true);
}
public function query()
{
$query = employee::select('ID','cNip','vName','vBankbranch');
return $this->applyScopes($query);
}
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction(['width' => '10%'])
->ajax('')
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['export', 'print', 'reset', 'reload'],
'initComplete' => "function () {
this.api().columns().every(function () {
var column = this;
var input = document.createElement(\"input\");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}",
]);
}
in View
#extends('layouts.app')
#section('content')
<div class="col-md-8 col-md-offset-2">
<h3>test</h3>
{!! $dataTable->table([], true) !!}
</div>
#endsection
#section('scripts')
{!! $dataTable->scripts() !!}
#endsection

Related

Change date format for Yajra Datatables as Service

I am using Yajra Datatables for Service for my Laravel project and wonder if i can use Carbon to change date format.
My datatables currently displaying date as bellow format
2020-11-11T16:03:13.000000Z
I want to display my date as
11-11-2020 03:13 PM
How can i do that. Please help.
My Datatables:
<?php
namespace App\DataTables;
// use App\App\OrderDataTable;
// use OrderDataTable;
use App\DataTables\OrderDataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
use App\Order;
use Illuminate\Support\Facades\DB;
class OrderDataTable extends DataTable
{
public function dataTable($query){
return datatables()
->eloquent($query);
}
public function query(OrderDataTable $model){
$from = date('2020-11-10 00:00:00');
$to = date('2020-11-11 23:59:59');
// $data = Order::where('created_at', '2020-11-11 22:03:13');
// $data = Order::select();
$data = Order::query()
// ->whereBetween('created_at', ['2020-11-10 00:00:00', '2020-11-11 23:59:59'])
->whereBetween('created_at', [$from, $to])
->select([
'orders.id',
'orders.ecomordid',
'orders.status_id',
'orders.awb',
'orders.created_at'
]);
return $this->applyScopes($data);
}
public function html(){
return $this->builder()
->setTableId('orderdatatable-table')
// ->columns($this->getColumns())
->columns([
'id' => [ 'title' => 'SHIPPING CODE' ],
'ecomordid' => [ 'title' => 'ECOM ORDER' ],
'status_id' => [ 'title' => 'STATUS' ],
'awb' => [ 'title' => 'AWB' ],
'created_at' => [ 'title' => 'DATE' ],
])
->minifiedAjax()
->dom('Bfrtip')
->orderBy(0)
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['excel', 'print', 'reset', 'reload'],
'initComplete' => "function () {
this.api().columns([0,3]).every(function () {
var column = this;
var input = document.createElement(\"input\");
$(input).appendTo($(column.footer()).empty())
.on('change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}",
]);
}
protected function getColumns(){
return [
Column::make('id'),
Column::make('ecomordid'),
Column::make('status_id'),
Column::make('awb'),
Column::make('created_at'),
];
}
protected function filename(){
return 'Order_' . date('YmdHis');
}
}
View:
#extends('layouts.master')
#section('content')
<meta name="csrf-token" content="{{ csrf_token() }}" />
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header bg-orange"><h3>{{ __('Update By AWB') }}</h3></div>
<div class="card-body">
<div class="table-responsive">
<div class="panel panel-default">
<div class="panel-heading">Sample Data</div>
<div class="panel-body">
{!! $dataTable->table([], true) !!}
{!! $dataTable->scripts() !!}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Controller
public function order(OrderDataTable $dataTable){
// dd($dataTable->request()->all());
return $dataTable->render('admin.search.order');
}
My current output
I am using:
Laravel: 7.28.4
laravel-datatables-buttons: 4.0
laravel-datatables-html: 4.0
laravel-datatables-oracle: 9.14
You can define an Accessor in Order model
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d H:i:s');
}
Note that it will work globally wherever you access created_at field it will be fetched with this format.
Read more about Accessors Here

Yajra DataTables service implementation upgrade from Laravel 5 to Laravel 6

We have been using Yajra DataTables with Laravel 5 for a few years and have built up a library of over 50 of them, basically for the index page of a BREAD UI. It's finally time to upgrade, and We're using the service implementation, which looks like this.
The current code is working against
"yajra/laravel-datatables-oracle": "^6.0",
Here is the Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\DataTables\WidgetDataTable;
use App\Models\Widget;
use Illuminate\Support\Facades\Auth;
use App\Models\Widgetaccount;
use App\Events\Widgetcrud;
use App\DataTables\WidgetHistoryDataTable;
use Illuminate\Support\Facades\DB;
class WidgetController extends Controller
{
/**
* Create a new controller instance
*
* #return void
*/
public function __construct()
{
$this->middleware('permission:widget_view', ['only' => ['index', 'history']]);
$this->middleware('permission:widget_create', ['only' => ['create','store']]);
$this->middleware('permission:widget_edit', ['only' => ['edit','update']]);
$this->middleware('permission:widget_delete', ['only' => ['destroy']]);
}
/**
* Display a listing of the resource.
*
* #param object $dataTable
* #return \Illuminate\Http\Response
*/
public function index(WidgetDataTable $dataTable)
{
return $dataTable->render('widget.index', [
'title' => 'Manage Widgets',
]);
}
// other methods here
}
Here is the DataTables class:
<?php
namespace App\DataTables;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Services\DataTable;
use Illuminate\Support\Facades\Auth;
class widgetDataTable extends DataTable
{
/**
* Display ajax rwidgetonse.
*
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->queryBuilder($this->query())
->editColumn(
'edit accounts',
function ($widget) {
return '<a href="' . route('widgetaccounts.index', 'widgetid=' . $widget->id)
. '" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> </a>';
}
)
->editColumn(
'documentation',
function ($widget) {
if ($widget->documentation != null) {
return '<a href="javascript:void(0)" data-value="' . $widget->documentation .
'" class="btn btn-xs btn-primary opendocument">View</a>';
} else {
return '';
}
}
)
->addColumn(
'action',
function ($widget) {
return '<a href="' . route('widgets.edit', $widget->id) .
'" class="btn btn-xs btn-primary" dusk="widget-edit-button-'.$widget->id .'"><i class="glyphicon glyphicon-edit"></i> Edit</a>
<a href="javascript:void(0)" data-remote="' . route('widgets.destroy', $widget->id) .
'" class="btn btn-xs btn-danger btn-delete" dusk="widget-delete-button-'.$widget->id .'"><i class="glyphicon glyphicon-trash"></i>Delete</a>';
}
)
->make(true);
}
/**
* Get the query object to be processed by dataTables.
*
* #return \Illuminate\Database\Eloquent\Builder|
*/
public function query()
{
$widget_id = null;
if ($this->request()->has("widgetid")) {
$widget_id = $this->request()->get("widgetid");
}
$query = DB::connection('dashboard')
->table('widgets')
->join('users', 'users.id', '=', 'widgets.user_id')
->whereNull('widgets.deleted_at')
->when($widget_id,
function ($queryvar, $widget_id) {
return $queryvar->where('widgets.id', $widget_id);
})
->select(
'widgets.id',
'widgets.name',
'widgets.active',
'users.name as username',
'widgets.documentation',
'widgets.created_at',
'widgets.updated_at',
'widgets.deleted_at'
);
return $this->applyScopes($query);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\Datatables\Html\Builder
*/
public function html()
{
if (Auth::user()->can('distribution_manage_widget_lists_edit')) {
return $this->builder()
->columns($this->getColumns())
->ajax('')
->addAction(['width' => '80px'])
->parameters([
'dom' => 'lBfrtip',
'buttons' => ['csv', 'excel'],
'pageLength' => 50
]);
}else{
return $this->builder()
->columns($this->getColumns())
->ajax('')
->parameters([
'dom' => 'lBfrtip',
'buttons' => ['csv', 'excel'],
'pageLength' => 50
]);
}
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
'id',
'name',
'active',
'documentation' => ['searchable' => false, 'orderable' => false],
'edit accounts' => ['searchable' => false, 'orderable' => false],
'last edited by' => ['name' => 'users.name', 'data' => 'username'],
'created_at',
'updated_at',
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'widgetdatatables_'.time();
}
}
Here is the view:
#extends('layouts.main')
#section('content')
#include('partials.panel-open', [ 'title' => "Manage widgets" ])
<form action="{{route('widgetsearch')}}" method="POST">
{{ csrf_field() }}
<div class="search_button_group">
<div class="row">
<div class="col-sm-4 col-sm-offset-2">
<label>Search for widget-related Settings: </label>
</div>
<div class="col-sm-6">
<div class="input-group">
<input type="text" class="form-control" placeholder="" name="search" aria-describedby="basic-addon1" required="required">
<button class="input-group-addon btn btn-primary" id="basic-addon1" type="submit">Go</button>
</div>
</div>
</div>
</div>
</form>
<div class="row form-group">
<div class="col-sm-6">
#permission(('widget_create'))
Add New widget
#endpermission
</div>
<div class="col-sm-6">
<div class="text-right">
widget History
</div>
</div>
</div>
{!! $dataTable->table(['class' => 'table table-bordered','id' =>'widget-table']) !!}
#permission(('widget_create'))
Add New widget
#endpermission
#include('partials.panel-close')
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Documentation</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#endsection
#push('scripts')
<script src="/vendor/datatables/buttons.server-side.js"></script>
{!! $dataTable->scripts() !!}
<script type="text/javascript">
$('#widget-table').on('click', '.btn-delete[data-remote]', function (e) {
e.preventDefault();
if (confirm("Are you sure you want to delete"))
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var url = $(this).data('remote');
$.ajax({
url: url,
type: 'DELETE',
dataType: 'json',
data: {method: '_DELETE', submit: true}
})
.always(function (data) {
var count = data.count;
if (count == 0) {
$('#widget-table').DataTable().draw(false);
} else {
alert("widget can't be deleted as there are associated widget Account/s (#" + count + ") under the same. Kindly remove the widget Account/s first.");
}
});
}
});
$(document).on("click",".opendocument",function(){
$(".modal-body").html($(this).data('value'));
$('#myModal').modal('show');
});
</script>
#endpush
Now I've updated composer and am trying to use:
"yajra/laravel-datatables-oracle": "^9.0",
"yajra/laravel-datatables-buttons": "^4.0",
And when I view the widget index, I get the ajax error dialog
DataTables warning: table id=widget-table -
Ajax error. For more information about this error,
please see http://datatables.net/tn/7
When I look in the Laravel.log:
[2020-07-24 10:30:55] local.ERROR: Call to a member function queryBuilder() on null
{"userId":19,"exception":"[object]
(Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function queryBuilder() on null at /Projects/my-app/app/DataTables/WidgetDataTable.php:20)
[stacktrace]
#0 [internal function]: App\\DataTables\\WidgetDataTable->ajax()
So, it seems that on this line:
return $this->datatables
->queryBuilder(...
the datatables property is not set. So, I am stuck as to how to proceed, and have broken my entire application. Looking for advice on what to try or a guide on how to upgrade the Yajra service implementation without having to modify hundreds of files.
It's been a while, but as I myself was stuck at this point in the process of upgrading, I thought I would share the solution as the documentation lacks a bit of detail.
I only got to understand what to change after finding and comparing this example sheet in the documentation:
https://yajrabox.com/docs/laravel-datatables/master/quick-starter
Further changes are then introduced in yajra's upgrade guide:
https://yajrabox.com/docs/laravel-datatables/8.0/upgrade
Changes to the DataTables class:
1.
/**
* Display ajax rwidgetonse.
*
* #return \Illuminate\Http\JsonResponse
*/
public function ajax()
{
return $this->datatables
->queryBuilder($this->query())
becomes:
use Yajra\DataTables\DataTables;
public function dataTable(DataTables $dataTables, $query) {
return $dataTables->eloquent($query)
If you're ajax / datatables function contains the ->editColumn() api, remove the ->render(); at the end. Otherwise html will be parsed as string.
3.
private function getColumns()
{
...
}
becomes protected:
protected function getColumns()
{
...
}
Return Object of the html function is now CamelCased too:
* #return \Yajra\Datatables\Html\Builder
to
* #return \Yajra\DataTables\Html\Builder
the getColumns() function now returns Columns as Array of Columns:
return [
[
'name' => 'users.firstname',
'data' => 'firstname',
'title' => 'Vorname',
],
];
becomes:
return [
Column::computed('firstname')
->name('users.firstname')
->title('Vorname'),
];
For which you need to import:
use Yajra\DataTables\Html\Column;
Even though that's the new way, your way of returning columns should still work as well.
Actually that's all
Many things are possible with sublime's find and replace so it shouldn't be that costly.
I hope that helps someone else who is struggling with the update.
Cheers
Dominik

Laravel problems with redirect

So I am working on a laravel project and I want that if a user types in their order code, the order will show up with the details. For some reason, the order code doesn't get through the if statement, because I get the output 'Order not found.' all the time, even if I type in an order code that is present in my orders table.
TrackController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
class TrackController extends Controller
{
public function index()
{
return view ('track.index');
}
public function show($id)
{
$order = Order::where('code', $id)->first();
return view('track.show',[
'order' => $order
]);
}
public function redirect(Request $request)
{
$orderCode = $request->input('order-track-id');
$order = Order::where('code', $orderCode)->first();
if(!$order){
return redirect('/track')->with('error', 'Order not found.');
}else{
return redirect('/track/' . $order->code);
}
}
}
web.php
Route::get('/track', 'TrackController#index');
Route::post('/track/redirect', 'TrackController#redirect');
Route::get('/track/{id}', 'TrackController#show');
track.index
#extends('layouts/app')
#section('content')
<div class="container">
<div class="row justify-content center">
{!! Form::open(['action' => 'TrackController#redirect', 'method' => 'post']) !!}
{!! csrf_field() !!}
<input type="number" name="input-order-track-id" id="order-track-id">
{{ Form::button('Track', ['type' => 'submit', 'class' => 'btn btn-primary'] ) }}
{!! Form::close() !!}
</div>
</div>
#endsection
What am I doing wrong and why isn't my function putting me through to the show function in the TrackController?
In your redirect controller function.
public function redirect(Request $request)
{
$orderCode = $request->input('input-order-track-id');
$orders = Order::where('code', $orderCode)->get();
if($orders->isEmpty()){
return redirect('/track')->with('error', 'Order not found.');
}else{
$order = Order::where('code', $orderCode)->first();
return redirect('/track/' . $order->code);
}
}

How to get Laravel api resource based data in Vue

I'm trying to show user projects list where user_id column is match with auth()->user()->id.
the problem i have is how to define what function of my resourced route to use.
Code
Controller
class ProjectController extends Controller
{
public function index()
{
$projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
return response()->json($projects);
}
public function userprojects()
{
$projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
return $projects;
}
}
Api route
Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);
Vue component
<template>
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Your Published Projects <span class="badge badge-info">{{projects.length}}</span></div>
<div class="card-body">
<ul>
<li v-for="project in projects" :key="project.id">
{{project.title}} - {{project.user_id}}
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data(){
return {
projects: []
}
},
created(){
this.fetchProjects();
},
methods:{
fetchProjects(){
var self = this;
axios.get('api/projects')
.then(function (resp) {
self.projects = resp.data;
})
.catch(function (resp) {
console.log(resp);
alert("Could not load projects");
});
},
},
}
</script>
Question
How do I tell my component to not load index function but to load
data from userprojects function?
So you could add a new route
Route::get('projects-user', 'Api\ProjectController#userprojects')->name('userprojects');
In js.
axios.get(Router('userprojects').url()).then(response => {
this.userprojects= response.data;
});
Also you could do just this in the controller
class ProjectController extends Controller
{
public function index()
{
if(Auth::check()){
$projects = Project::orderby('id', 'desc')->where('user_id', '=', Auth::user()->id)->get();
}else{
$projects = Project::orderby('id', 'desc')->latest()->take(10)->get();
}
return response()->json($projects);
}
}
You can create a new route before the resource route and use it:
Route::get('projects/me', 'Api\ProjectController#userprojects', ['except' => ['create', 'edit', 'destroy']]);
Route::resource('projects', 'Api\ProjectController', ['except' => ['create', 'edit', 'destroy']]);
then on your component:
axios.get('api/projects/me')
.then(function (resp) {
self.projects = resp.data;
})

laravel API, not fetching data from DB

This is on production side (on unbtu Digital Ocean server)
"laravel: 5.3"
"php": "5.5.9"
Route path : /route/web.php (not in middleware)
Route::get('api/getsymbol-request','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request){
$symbol = DB::table("symbols")
->where("market_id", $request->market_id)
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
http://yourtradelog.com/api/getsymbol-request?market_id=1 //This is not working url I am getting issue WHY THIS IS NOT WORKING
http://yourtradelog.com/api/getsymbol //This is working url
Database tables
<script>
$(document).ready(function() {
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/getsymbol-request/')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
}
});
});
</script>
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbol:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options'] , null, ['class'=>'symbol_id', 'id'=>'symbol','data-width'=>'60%', 'data-live-search'=>'true'] )!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
I prefer using route parameters like this (see more in the documentation here):
Routes:
Route::get('api/getsymbol-request/{id}','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request, $id){
$symbol = DB::table("symbols")
->where("market_id", $id)
->get()
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
Please note that the URL has changed to this format:
http://yourtradelog.com/api/getsymbol-request/1
Try to this code:
public function getSymbolRequest(Request $request)
{
$marketID = (int)$request->get('market_id')
$symbol = DB::table('symbols')
->where('market_id', $marketID)
->get(['symbol','id']);
return response()->json($symbol);
}
public function getSymbol()
{
$symbol = DB::table('symbols')
->get(['symbol','id']);
return response()->json($symbol);
}

Resources