Laravel datatable row details - laravel

I am using a single datatable in Laravel 5.4 since it is already implemented in the Laravel framework. My datatable is using query builder to get data, for example using something like this:
#section('content')
<div class="container">
<table id="services" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th> </th>
<th>Id</th>
<th>Plate</th>
<th>Brand</th>
<th>Year</th>
</tr>
</thead>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
table = $('#services').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{ route('datatable_ser.getdata') }}",
"columns": [
{data: 'id', name: 'id'},
{data: 'plate', name: 'plate'},
{data: 'brand', name: 'vehicle.brand'},
{data: 'year', name: 'vehicle.year'},
]
});
});
</script>
#stop
And to get it working proberly, I have to include this file:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Since datatables are included in Laravel, it takes css from bootstrap, javascript from the datatables package installed in laravel.
Now, reading row detail documentation it is a bit unclear, how can I achieve row details in my case. What do I have to add into the code? Do I have to include some more files?
Same with other features as Edit or Remove buttons for each row. Laravel itself doesn't have documentation for datatables so it is a bit confusing what to do now. Thanks for help.

So in my view, I put an ajax function to call the data.
$('#pesquisarFinal').submit(function(e){
e.preventDefault();
url = '{{ route("disciplina.criar.ano.novo",["curso" => ":id"]) }}';
url = url.replace(":id", $("#curso").val());
$.ajax({
method: "POST",
url: url,
data: {
'_token': '{{ csrf_token() }}',
curso: $('#curso').val(),
nivel: $('#nivel').val(),
semestre: $('#semestre').val()
}
}).done(function(msg){
oTable.clear().draw();
oTable.rows.add(msg.data).draw();
});
})
In my controller, I did like this to call the rows to insert into the table
public function criarNovoAno(Request $request, Curso $curso){
$curso = Curso::find($request->curso);
$dados = Array();
foreach($curso->disciplina as $item){
$check = '<input type="checkbox" value="'.$item->pivot->id.'" class="flat atribuir"/>';
if($request->semestre == $item->pivot->semestre->idsemestre && $request->semestre == $item->pivot->nivel->idnivel){
array_push($dados,[$check,$item->codigo, $item->nome, $item->pivot->semestre->descricao, $item->pivot->nivel->descrico, $curso->nome]);
}
}
return response()->json(["data" => $dados]);
}
in the controller, I create an array, when the loop start I create a new array for each position in the first array.
Final result

Related

Can i store database tables to a data table?

i want to store my database table in a data table is that possible?
my controller
$tablemonth = \DB::select("SHOW TABLES WHERE Tables_in_database LIKE '%Month_Report_%'");
my blade without data table
<table id="listoftable" class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>File Name</th>
</tr>
</thead>
<tbody>
#foreach($tablemonth as $table)
<tr>
<td>
{{$table->Tables_in_database}}
</td>
</tr>
#endforeach
</tbody>
</table>
Trying to achieve like this
<script>
$(function() {
var table = $('#listoftable').DataTable({
processing: false,
serverSide: true,
ajax: '{!! route('admin.get.table') !!}',
columns: [
{ data: {{tablemonth}}, name: {{$tablemonth}} },
]
});
});
</script>
Database table
I suggest looking into https://github.com/yajra/laravel-datatables, which allows to use the following result as input for the DataTables:
$data = \DB::select("SHOW TABLES WHERE Tables_in_database LIKE '%Month_Report_%'");
return Datatables::of($data)->addIndexColumn()->make(true);
Create a controller using the snippet above and consume it via the following DataTables initialization:
<script>
$(function() {
$('#listoftable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('API-route-name') }}',
columns: [
{ data: 'Tables_in_database', name: 'Table name' }
]
});
});
</script>
See https://www.itsolutionstuff.com/post/laravel-58-datatables-tutorialexample.html for a tutorial.

Laravel : Update Database using Ajax. What's I should to do next?

I need the guidance of somebody to help me building the function Update Database when using AJAX. When I click the button Accept so an Ajax request will send to the server and server will execute UPDATE value of field post_status. At the start, field post_status has value is "pending", and after execute query UPDATE so the value will change to "accepted".
What's I should do next? Please help me.
Thank you so much for help.
The database of the Posts table:
post_id user_id title content DateTime post_status
1 1 Title 1 Content 1 Time pending
2 2 Title 2 Content 2 Time pending
3 3 Title 3 Content 3 Time pending
4 4 Title 4 Content 4 Time pending
5 5 Title 5 Content 5 Time pending
The View:
<table class="table table-bordered">
<thead class="thead-inverse">
<tr>
<th>Post ID</th>
<th>User ID</th>
<th>Name User</th>
<th>Title</th>
<th>Content</th>
<th>Datetime</th>
<th>Status</th>
<th>Accept</th>
</tr>
</thead>
<tbody>
#foreach ($posts as $row)
<tr id="{{ $row->post_id }}">
<td>{{$row->post_id}}</td>
<td>{{$row->user_id}}</td>
<th>{{$row->users->name}}</th>
<td>{{$row->post_title}}</td>
<td>{{$row->post_content}}</td>
<td>{{$row->post_datetime}}</td>
<td>{{$row->post_status}}</td> {{-- The status of post that I wanna change the value to "accepted" --}}
<td>
<button class="btn btn-success accept-btn" data-postID="{{$row->post_id}}">Accept</button>
</td>
</tr>
#endforeach
</tbody>
</table>
The code Javascript:
<script>
$(document).ready(function () {
$('.accept-btn').click(function(){
var postId = $(this).attr('data-postID');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
},
});
})
});
</script>
The function list_post_ajax of Controller:
public function list_post_ajax(Request $request)
{
if(request()->ajax()){
$postId = $request->get('postId');
return response()->json(['success'=>$postId]);
// What's I should do next?
// Pls help me.
}
}
There are so many ways to do it. This one will work following your code. Use $myObject->save(); to save a new record or update a old one.
Change on view
<td id="td{{$row->post_id}}">{{$row->post_status}}</td>
On Controller
$postId = $request->get('postId');
$post = App\Post::find($postId);
$post->post_status= 'accepted';
$post->save();
return response()->json(['success'=>$postId,'message'=>'accepted']);
On JS
$.ajax({
type: "POST",
url: "{{route('posts.list_post_ajax')}}",
data: { postId: postId },
dataType: 'JSON',
success :function(response) {
console.log(response);
$('td'+postId).html(response.message);
},
});
Edit: I update my answer on Controller. You should take a look Eloquent Documentation

JSON showing instead of Datatable following Ajax call to Laravel Controller

I’m fairly new to ajax and json and would really appreciate some help.
I’m making an Ajax call to a Laravel Controller to return some fields from a database table called "subjects" and display them in a DataTable in a Laravel View. The problem is that when I open the view, what is see is JSON rather than the Datatable.
Here’s what’s returned in the view subjects/index:
{"draw":0,"recordsTotal":8,"recordsFiltered":8,"data":[{"id":"1","name":"Biology"},{"id":"3","name":"English Language"},{"id":"4","name":"Physics"},{"id":"5","name":"Chemistry"},{"id":"6","name":"Mathematics"},{"id":"7","name":"Mathematics"},{"id":"8","name":"English Language"},{"id":"9","name":"French"}],"queries":[{"query":"select count(*) as aggregate from (select '1' as `row_count` from `subjects`) count_row_table","bindings":[],"time":4.65},{"query":"select `id`, `name` from `subjects`","bindings":[],"time":0.41}],"input":[]}
Here’s the HTML in the view /subjects/index
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Here’s the code in the Laravel Controller:
class SubjectsController extends Controller
{
public function index()
{
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
}
Here’s the code making the Ajax call:
$('#subjects_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{route('subjects.index')}}",
"columns":[
{"data": "id"},
{"data": "name"}
]
});
Here’s the route definition in web.php:
Route::get('subjects/', 'SubjectsController#index')->name('subjects.index');
Any help you can provide would be really appreciated
You should try this:
Routes
Route::get('subjects', 'SubjectsController#index')->name('subjects.index');
Route::get('getsubjects', 'SubjectsController#getSubjects')->name('subjects.get');
SubjectsController
class SubjectsController extends Controller
{
public function index()
{
return view('subjects.index');
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
public function getSubjects()
{
return \DataTables::of(Subject::query())->make(true);
}
}
View
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#subjects_table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('subjects.get') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
]
});
});
</script>

Cannot read property replace of null method parameter

I started messing around with Vue.js earlier this week.
So far I created a list of MTG(a TCG) cards. The data comes from the database through an Ajax request. This all works like a charm.
What i want to do next is replace the string that contains the costs of a card e.g. something like '{1}{U}{G}' with images for the corresponding tag.
HTML:
<div v-for="(cards, key) in mainBoard" class="">
<table class="table">
<tr>
<th colspan="5">#{{ key }}</th>
</tr>
<tr>
<th>#</th>
<th>Name</th>
<th>ManaCost</th>
#if($deck->enableCommander())
<th>Commander</th>
#else
<th></th>
#endif
<th>Actions</th>
</tr>
<tr v-for="card in cards">
<td>#{{card.pivot.quantity}}</td>
<td>#{{card.name}}</td>s
<td v-html="replaceManaSymbols(card)"></td>
#if($deck->enableCommander())
<td>
<span v-if="card.pivot.commander" #click="preformMethod(card, 'removeCommander', $event)"><i class="fa fa-flag"></i></span>
<span v-else #click="preformMethod(card,'assignCommander', $event)"><i class="far fa-flag"></i></span>
</td>
#else
<td> </td>
#endif
<td>
<button #click="preformMethod(card,'removeCardFromDeck', $event)"><i class="fa fa-times-circle"></i></button>
<button #click="preformMethod(card,'plusCardInDeck', $event)"><i class="fa fa-plus-circle"></i></button>
<button #click="preformMethod(card,'minusCardInDeck', $event)"><i class="fa fa-minus-circle"></i></button>
</td>
</tr>
</table>
</div>
Vue.js
new Vue({
el: '#Itemlist',
data: {
mainBoard: [],
sideBoard: [],
},
methods:{
preformMethod(card, url){
var self = this;
var varData = {
slug: '{{ $deck->slug }}',
card: card.id,
board: card.pivot.mainboard
};
$.ajax({
url: '/vue/'+url,
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
},
replaceManaSymbols(card){
var mc = card.manaCost;
var dump = mc.replace(/([}])/g, '},').split(',');
var html = '';
/**
* replace each tag with an image
*/
return html;
}
},
mounted(){
var self = this;
var varData = {
slug: '{{ $deck->slug }}'
};
$.ajax({
url: '/vue/getDeckList',
data: varData,
method: 'GET',
success: function (data) {
self.mainBoard = data.mainBoard;
self.sideBoard = data.sideBoard;
},
error: function (error) {
console.log(error);
}
});
}
})
I pass the card as a parameter to the replaceManaSymbols method. I can console.log the contents of mana without any issue. But as soon as a want to modify the string Vue throws the error TypeError: Cannot read property 'toLowerCase/split/replace' of null. I'm not really sure what's going wrong. Any idea's?
As a rule of thumb, you shouldn't use methods on the display side. Keep them for the update side - processing changes back into a store and such. Methods aren't reactive - they need to be called. You want your display to automatically reflect some underlying data, so you should use computed.
You should also avoid using v-html, because you end up with markup outside your templates, and that markup is static. It's not totally clear to me what will be in v-html, but you should try and keep markup in your template, and inject values using data, props or computed. Hope this helps!
If you want a div with some text that magically turns into an image tag, this could be a good use for <component :is>.

Bind Vue click function on dynamically created content from jquery

First of all I am new to vuejs., currently working on a project made using Laravel. I am using Vue where ever I feel the need for it. On a certain page I am using datatable to load list of machine requests
$list = LicenceRequests::orderBy('allocated')->with('users.userDetails')->where('users_id', '!=', 1)->get();
return Datatables::of($list)
->addColumn('actions', function ($list) {
return '<button data-id="'.$list->id.'" class="btn btn-success" #click="allocateEvent">Allocate</button>';
})
->addIndexColumn()
->rawColumns(['actions'])
->make(true);
I have added a click function so that When the datatable is rendered, a Vue function can be called. In the blade template, I am using the following html code :
<div id="content" class="content">
<div class="block">
<div class="block-content">
<table class="table table-bordered table-striped " id="requestList">
<thead>
<tr>
<th>Sr. No</th>
<th class="hidden-xs" >Name</th>
<th class="hidden-xs" >Email</th>
<th class="hidden-xs" >Requests</th>
<th class="hidden-xs" >Allocated</th>
<th class="hidden-xs" >Date requested</th>
<th class="hidden-xs" >Machine address</th>
<th class="text-center">Actions</th>
</tr>
</thead>
</table>
</div>
</div>
</div>?
For the datatable, I am calling it on the page load function as follows :
$(function (){
$('#requestList').dataTable({
processing: false,
serverSide: true,
ajax: '{!! route('admin.getLicenceRequests') !!}',
columns: [
{data: 'DT_Row_Index', orderable: false, searchable: false},
{ data: 'users.user_details.name', name: 'name' },
{ data: 'users.email', name: 'email' },
{ data: 'number', name: 'number' },
{ data: 'allocated', name: 'allocated' },
{ data: 'request_generated_on', name: 'request_generated_on' },
{ data: 'machine_address', name: 'machine_address' },
{ data: 'actions', name: 'actions',orderable: false, searchable: false }
],
lengthMenu: [[ 10, 15, 20], [ 10, 15, 20]]
});
});
I am initializing Vue on the same page
var vm = new Vue({
el: '#content',
methods: {
allocateEvent: function() {
console.log("hello");
}
}
})
The problem is that the function is not called when I press the button on the rendered html of datatable. If I bind the function to any otehr element fn the page it will work. Is there something I am missing or some Vue related code that I am not adding?
P.S I know this is not how Vue should be used with laravel blade. I just wanted to know why the above code is not working when it should.
Thanks
I don't think you can create a binding with dynamically rendered content like this. The problem is the vue application is created first and the content with the #click binding is rendered afterwards.
Here is a comment by Evan Yu regarding dynamic content:
https://forum-archive.vuejs.org/topic/151/vue-js-not-listening-to-dynamically-created-elements
It's suggested to use $compile(html) and appendChild when working with dynamic content.

Resources