I am trying to fetch data using datatable in laravel. My
view is :
<script type="text/javascript">
var oTable;
$(document).ready(function () {
oTable = $('#data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"columns":[
{"data":"start_date"},
{"data":"end_date"},
{"data":"client_id"},
{"data":"created_at"},
{"data":"actions"}
],
"ajax": "{{ url('contract') }}" + ((typeof $('#data').attr('data-id') != "undefined") ? "/" + $('#id').val() + "/" + $('#data').attr('data-id') : "/data")
});
});
function deleteClient(id){
}
</script>
public function data(Datatables $datatables)
{
$contObj = new Contract;
$conttt = $contObj->get()
->map(function ($conttt) {
return [
'id' => $conttt->id,
'start_date' => $conttt->start_date,
'end_date' => $conttt->end_date,
'client_id' => $conttt->user_id,
'created_at' => $conttt->created_at
];
});
return $datatables->collection($conttt)
->addColumn('actions', '#if(Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/edit\' ) }}" title="{{ trans(\'table.edit\') }}">
<i class="fa fa-fw fa-pencil text-warning "></i> </a>
#endif
<a href="{{ url(\'contract/\' . $id . \'/show\' ) }}" title="{{ trans(\'table.details\') }}" >
<i class="fa fa-fw fa-eye text-primary"></i> </a>
')
->removeColumn('id')
->rawColumns(['actions'])->make();
}
but when I am getting this data as :
"data":[{"start_date":null,"end_date":null,"client_id":"3","created_at":{"date":"2018-08-07 10:13:46.000000","timezone_type":"3","timezone":"UTC"},"actions":" <a href=\"http:\/\/billing.mj.milesweb.cloud\/files\/public\/contract\/1\/edit\" title=\"Edit\">\n <i class=\"fa fa-fw fa-pencil text-warning \"><\/i> <\/a>\n <a href=\"http:\/\/billing.mj.milesweb.cloud\/files\/public\/contract\/1\/show\" title=\"Show\" >\n <i class=\"fa fa-fw fa-eye text-primary\"><\/i> <\/a>\n "}
When I see this data in datatable then I see in field created_at the data shown there is [object Object] while in json it is OK. Please help me to show the proper data in datatable
It's because created_at is a Carbon object and you need a string. For 'created_at', try returning the following:
\Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $conttt->created_at)->format('m/d/y h:i A')
By default created_at and updated_at are the carbon class object. You need to convert it into your own format:
$conttt = $contObj->get()
->map(function ($conttt) {
return [
'id' => $conttt->id,
'start_date' => $conttt->start_date,
'end_date' => $conttt->end_date,
'client_id' => $conttt->user_id,
'created_at' => $conttt->created_at->format('d-m-Y')
];
});
You also can write this code into Your model class. For that you need to user Laravel mutators.
Good Luck!!!
you can editColoumn in datatable like this:
return Datatables::of($conttt)
->editColumn('created_at', function($conttt) {
return $conttt->created_at->format('d M Y H:i:s');
})
->make(true);
try it
1)
$contObj = new Contract;
$conttt = $contObj->get()
->map(function ($conttt) {
return [
'id' => $conttt->id,
'start_date' => $conttt->start_date,
'end_date' => $conttt->end_date,
'client_id' => $conttt->user_id,
'created_at' => date('Y-m-d h:s:i', strtotime($conttt->created_at))
];
});
2)
$contObj = Contract::all();
Related
I need to store my images in the database in one column dynamically I have no idea how to do it please help me. thank you in advance here is my view controller and model. Here is an image, Below there are an array that on Choose File Button. I want to store them into the database in a column how to do that?
My Database Table name is InflightMagazine
My VIEW code
{!! Form::open(['action'=>'Admin\InflightMagazines#store', 'method' => 'POST','enctype'=>'multipart/form-data']) !!}
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr class="form-row">
<td> <b>{{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}}</b><br>
{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}
{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}
</td>
<td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle add', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
</tr>
</table>
{{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
</div>
{!! Form::close() !!}
AJAX / JQuery Code
<script>
$(document).ready(function() {
var len = $('.form-row').length;
$(document).on('click', '.add', function() {
$('#dynamic_field').append('<tr class="form-row" data-id="'+len+'"><td> {{ Form::text('inflightmagz_date[]', date('F Y') , ['class' => 'form-control', 'id'=>"exampleFormControlFile1"])}} <br> {{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }} {{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle addFile', 'id'=>'addFile','name'=>'addFile', 'style'=>'font-size:15px;']) }}</td><td><button type="button" name="remove" class="btn btn-danger fa fa-minus-circle btn_remove_all"></button></td></tr>');
});
$(document).on('click', '.submit', function() {
$.ajax({
method: "POST",
data: $('#add_name').serialize(),
success: function(data) {
alert(data);
$('#add_name')[0].reset();
}
});
});
$(document).on('click', '.addFile', function() {
var id = $(this).closest('.form-row').data('id');
var elem = '<tr class="'+id+'"><td>{{ Form::file('infightmagazine_pdf[]',['id'=>'exampleFormControlFile1']) }}<button type="button" name="remove" class="btn btn-danger btn_remove fa fa-minus-circle"></button></td></tr>';
$(elem).insertAfter($(this).closest('tr'));
});
$(document).on('click', '.btn_remove, .btn_remove_all', function() {
if($(this).hasClass('btn_remove_all')){
var id = $(this).closest('.form-row').data('id');
$('tr.'+id).remove();
}
$(this).closest('tr').remove();
});
});
</script>
Controller Storing Function code
public function store(Request $request){
$this->validate($request, [
'inflightmagz_date' => 'required',
'infightmagazine_pdf' => 'required'
]);
if ($request->has('infightmagazine_pdf')){
//Handle File Upload
$inflightmags = [];
foreach ($request->file('infightmagazine_pdf') as $key => $file){
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/infightmagazine_pdfs',$fileNameToStore);
array_push($inflightmags, $fileNameToStore);
}
$fileNameToStore = serialize($inflightmags);
}
}
I think what you are looking for is attribute casting to array
https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
this will allow you to save an array of file locations to a single field in the DB and retrieve them as an array
I would remove the serialise on the $fileNamesToStore
Hope this helps
I am new to laravel, I have written a route
Route::resource('contract', 'ContractController');
Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
});
My controller file is :
public function data(Datatables $datatables)
{
$contracts = $this->contractRepository->getAll()
->get()
->map(function ($contract) {
return [
'id' => $contract->id,
'start_date' => $contract->start_date,
'end_date' => $contract->end_date,
'description' => $contract->description,
'name' => '',
'user' => '',
];
});
return $datatables->collection($contracts)
->addColumn('actions', '#if(Sentinel::getUser()->hasAccess([\'contracts.write\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/edit\' ) }}" title="{{ trans(\'table.edit\') }}">
<i class="fa fa-fw fa-pencil text-warning"></i> </a>
#endif
#if(Sentinel::getUser()->hasAccess([\'contracts.read\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/show\' ) }}" title="{{ trans(\'table.details\') }}" >
<i class="fa fa-fw fa-eye text-primary"></i> </a>
#endif
#if(Sentinel::getUser()->hasAccess([\'contracts.delete\']) || Sentinel::inRole(\'admin\'))
<a href="{{ url(\'contract/\' . $id . \'/delete\' ) }}" title="{{ trans(\'table.delete\') }}">
<i class="fa fa-fw fa-times text-danger"></i></a>
#endif')
->removeColumn('id')
->escapeColumns( [ 'actions' ] )->make();
}
When I am running with url contract/data then I am getting 404 not found error. In console I am getting error also
No query results for model [App\Models\Contract].
Please help me to resolve the issue
Just remove Route::resource('contract', 'ContractController'); or put that after Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
}); like so:
Route::group(['prefix' => 'contract'], function () {
Route::get('data', 'ContractController#data');
});
Route::resource('contract', 'ContractController');
You get 404 on route /contract/data because the router is actually directed into contract/{contract} in ContractController#show from the upper routes on Route::resource('contract', 'ContractController');
Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}
This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.
This is my route
Route::get('/view/{id}', [
'uses' => 'ClientController#view',
'as' => 'view'
]);
This is my Client controller
public function view($id){
$client = Client::where('id',$id)->first();
return view('view',compact('client'));
}
This is my datatable
#extends('layouts.datatables_master')
#section('content')
<table class="table table-bordered" id="clients-table">
<thead>
<tr>
<th>ID</th>
<th>Company Name</th>
<th>Name</th>
<th>Surname</th>
<th>ID Number</th>
<th>Created</th>
<th>Last Updated</th>
<th>Actions</th>
</tr>
</thead>
</table>
#stop
#push('scripts')
<script>
$(function() {
$('#clients-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('business.list') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'companyname', name: 'companyname' },
{ data: 'name', name: 'name' },
{ data: 'surname', name: 'surname' },
{ data: 'idnumber', name: 'idnumber' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' },
{ data: "actions",
"render": function(data, type, row) {
return '<i class="fa fa-search" title="View"></i> <i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i> <i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>'
;}
}
]
});
});
</script>
#endpush
Problem
My Main issue is passing an ID for all users. If you check my render function on my DataTable I said return route(view,1) where it's 1. I want to pass $id but it says undefined variable. Please help.
You could return the generated route link from your controller like:
return datatables(Client::query())
->addColumn('actions', function ($client) {
return [
'edit_link' => route('view', [$id => $client->id]),
];
})->toJson();
and render in your view as
{
data: "actions",
render: function(data, type, row) {
return
'<a href="' + data.edit_link + '" class="btn btn-xs btn-info">' +
'<i class="fa fa-search" title="View"></i></a>' +
'<a href="#" class="btn btn-xs btn-primary">' +
'<i class="fa fa-pencil" data-toggle="tooltip" data-placement="top" title="Edit"></i>' +
'</a>' +
'<a href="#" class="btn btn-xs btn-danger">' +
'<i class="fa fa-trash" data-toggle="tooltip" data-placement="top" title="Delete"></i>' +
'</a>';
}
}
the value of data should be an 'id', and use url() instead of route() :
{ data: "id",
"render": function(data, type, row) {
return '<a href="{{ url("view") }}/"'+ data +'>View</a>';
}
}
Try like this
return '<i class="fa fa-search" title="View"></i>
You pass the client variable to blade
{{ route('view',$client->id); }}
I'm using Yajra datatable, I had an issue as what title said.
here's my controller so far :
public function makeActionButtonsForDatatable($model)
{
if ($model->employed_type == DriverEmployedType::PARTTIME) {
return '<a href="' . route('parttimeavailable.create', ['driver' => $model->id]) . '"
class="btn btn-default btn-xs"></span>Set Parttime
</a>
<a href="' . route('driver.edit', ['driver' => $model->id]) . '"
class="btn btn-primary btn-xs"><span class="fa fa-pencil"></span> Edit
</a>
<a id="delBtn" data-url="'.route('driver.destroy', ['driver' => $model->id]).'"
data-toggle="modal" data-target=" #modalDelete" data-title="Confirmation" data-table-name="#datatable" data-message="Do you want to delete this record?"
class="btn btn-danger btn-xs delete" >
<span class="fa fa-trash-o"></span> Delete
</a>';
}
switch ($model->status) {
default:
return'
<a href="' . route('driver.edit', ['driver' => $model->id]) . '"
class="btn btn-primary btn-xs"><span class="fa fa-pencil"></span> Edit
</a>
<a id="delBtn" data-url="'.route('driver.destroy', ['driver' => $model->id]).'"
data-toggle="modal" data-target=" #modalDelete" data-title="Confirmation" data-table-name="#datatable" data-message="Do you want to delete this record?"
class="btn btn-danger btn-xs delete" >
<span class="fa fa-trash-o"></span> Delete
</a>
';
break;
}
}
public function makeDatatable($obj) {
return Datatables::of($obj)
->addColumn('action', function ($model) {
return $this->makeActionButtonsForDatatable($model);
})
->editColumn('full_name', function($model) {
return '<a href="' . route('driver.edit', ['driver' => $model->full_name]) . '"</a>';
})
->editColumn('employed_type', function($model){
return DriverEmployedType::getString($model->employed_type);
})
->make(true);
}
and here's my datatable code so far :
$(document).ready(function(){
var datatable = $('#datatable').DataTable(
{
dom: "lrtip",
responsive: true,
processing: true,
serverSide: true,
bSortCellsTop: true,
ajax: {
url: "{{ route('driver.list') }}",
data: { '_token' : '{{csrf_token() }}'},
type: 'POST',
},
columns: [
{ data: 'full_name', name: 'full_name', className: 'text-center', },
{ data: 'mobile', name: 'mobile', className: 'text-center', },
{ data: 'nric', name: 'nric', className: 'text-center', },
{ data: 'license', name: 'license', className: 'text-center', },
{ data: 'employed_type', name: 'employed_type', className: 'text-center', },
{ data: 'action', name: 'action', className: 'text-center', orderable: false, searchable: false },
],
});
});
It didn't works, and didn't display my fullname column. I want is once I click the name it goes to edit form with that driver Id.
any idea ?
I think you missed to close <a> for fullName column, try below code:
public function makeDatatable($obj) {
return Datatables::of($obj)
->addColumn('action', function ($model) {
return $this->makeActionButtonsForDatatable($model);
})
->editColumn('full_name', function($model) {
return ''. $model->full_name .'';
})
->editColumn('employed_type', function($model){
return DriverEmployedType::getString($model->employed_type);
})
->make(true);
}
Let me know if you still facing the same!