I am using datatable yajra package in my project lravel 5.1 and wants to get data through laravel eloquent this is my suggestion model code.
public function candidate()
{
return $this->belongsTo('App\Candidate', 'suggested_user');
}
And this is controller code.
public function getBCReport()
{
$candidates = \App\Suggestion::with('candidate')->get();
return Datatables::of($candidates)
->make(true);
}
And this is my view code:
<
div class="panel-body">
<div class="candidatereport">
<div class="table-responsive">
<table class="table display" id="table_id" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</section>
<script>
$(function() {
$('#table_id').DataTable({
processing: true,
serverSide: true,
dataType: 'json',
ajax: '{!! route('datatables.candidatereport') !!}',
columns: [
{ data: 'candidate.fname', name: 'fname' },
{ data: 'candidate.lname', name: 'lname' },
]
});
});
</script>
In controller when I use this code
$candidates = \App\Suggestion::with('candidate');
According to datatable yajra documentation
http://datatables.yajrabox.com/eloquent/relationships
it’s not working butt when I use with
$candidates = \App\Suggestion::with('candidate')->get();
Its working butt this is not according to datatable yajra documentation.
Can any one tell what is the reason behind this. Thanks
When using eloquent models, the get() method is used when there are constraints added to query.
In your question you want to know why that worked in the example given in documentation for yajra. And the reason is, they have returned the data table from the eloquent model itself. Whereas, you are creating the datatable at controller level. So get() method is necessary for controller to retrieve the results out of this eloquent relation.
See the link. Under the Retrieving Multiple Models, the use of get is explained.
Here you will find my detailed answer, I have mentioned, Controller method, View structure, Datatable JS code, Have a look
Follow Stack overflow answer
Related
As the title says with other controller and view I can send the data but I can't with the controller and view I'm gonna post below.
Controller code (Its a resource controller but I'm using a custom function)
<?php
namespace App\Http\Controllers;
use App\Models\Persona;
use Illuminate\Http\Request;
class PersonaController extends Controller
{
public function mostrarMedicos(){
$medicos = Persona::where('idTipoPersona', 4)->get();
return view('gestionMedicos',compact($medicos));
}
}
View Code
#extends('layouts.app')
#section('content')
<h1>Gestión Médicos</h1>
<div class="container">
<table class="table table-bordered table-hover">
<tr class="info">
<th>Nombre</th>
<th>Apellido</th>
<th>Cedula</th>
<th>Email</th>
<th>Teléfono</th>
<th>Dirección</th>
<th>Ciudad Residencia</th>
<th>Fecha de Nacimiento</th>
<th>Género</th>
</tr>
#foreach ($medicos as $medico)
<tr>
<td>{{$medico->nombre}}</td>
<td>{{$medico->apellido}}</td>
<td>{{$medico->cedula}}</td>
<td>{{$medico->email}}</td>
<td>{{$medico->telefono}}</td>
<td>{{$medico->direccion}}</td>
<td>{{$medico->ciudadResi}}</td>
<td>{{$medico->fechaNacimiento}}</td>
<td>{{$medico->genero}}</td>
</tr>
#endforeach
</table>
Route
Route::get('/gestionarMedicos', [PersonaController::class,'mostrarMedicos'])->name('personaMostrarMedicos');
This is the error I'm getting
Undefined variable $medicos (View: D:\xampp\htdocs\SistemaHNF\resources\views\gestionMedicos.blade.php)
Im new on Laravel and I don't understand why I get this error if from what I can understand the controller is supossed to return the view with the $medicos variable that should have the data.
(English is not my main language so sorry for any mistake and also I can post any extra code or explain in more detail something if needed).
You have return query builder and forgotten to call get() or first() and also wrong with compact
public function mostrarMedicos(){
$medicos = Persona::where('idTipoPersona', 4)->get();
return view('gestionMedicos',compact('medicos'));
}
Im building a app the shows information of a survey results. In each survey i have questions, and each question have his answers.
But im having some issues on building the table, the header table and the body is build dynamacly, where the header is the questions, and the body are the answers.
Examle of my code table:
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
#foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($survey->answers->groupBy('email') as $answer)
<tr>
#foreach($answer as $a)
<td>{{$a->answer}}</td>
#endforeach
</tr>
#endforeach
</tbody>
<tfoot>
#foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
#endforeach
</tfoot>
</table>
The only problem that im having is the syncronization between the header label questions and above that are the answers, sometimes the answer if a question is sort in a diferent order, for example is not in the correct position.
Cant figure out what im doing wrong, above i leave the tables, maybe someone can have a idea what im doing wrong.
Tables:
surveys:
- id;
- name;
questions:
- id;
- survey_id;
- label;
- internal_name;
answers:
- id;
- survey_id;
- question_id;
- answer
- email;
Question Model:
class Question extends Model
{
public function survey()
{
return $this->belongsTo(Survey::class);
}
public function answers() {
return $this->hasMany(Answer::class);
}
public function oneAnswer(){
return $this->hasOne(Answer::class);
}
}
Answer Model:
class Answer extends Model
{
public function survey() {
return $this->belongsTo(Survey::class);
}
public function question() {
return $this->belongsTo(Question::class);
}
}
Screenshot
According to my understanding, do an order by question_id. Also noticing that you are querying three times, I suggest query one time & store it in a variable and use it.
#php
$results = $survey->answers->groupBy('email')->orderBy('question_id');
#endphp
...
#foreach($results->first() as $answer)
...
I am trying to implement pagination in laravel and got following error
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name
Here is my controller function
public function showTags($id)
{
$tag = Tag::find($id)->paginate(5);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc');
}]);
return view('blog.showtags')->withTag($tag);
}
Here is the Tag Model
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany('App\Post');
}
}
The Tag and Post model has belongsToMany Relationship so there are many posts under the specific tag and my aim is to iterate all posts under the specific tags descending order of post and also to implement pagination in that page.
Here is the code for showtags view
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
<?php $count = 1; ?>
#foreach($tag->posts as $post)
<tr>
<th>{{ $count++ }}</th>
<th>{{ $post->title }}</th>
<th>#foreach($post->tags as $tag)
<span class="label label-default">{{ $tag->name }}</span>
#endforeach
</th>
</tr>
#endforeach
</tbody>
</table>
//Here is the code i used for pagination in view
<div class="text-center">
{!! $tag->posts->links() !!}
</div>
If anybody know how to do this please respond. Thanks in advance.
I solve the problem by using a simple trick. My aim was to paginate all posts under the same tags just like you guys can see in StackOverflow.
The modified controller function is
public function showTags($id)
{
$tag = Tag::find($id);
// when lazy loading
$tag->load(['posts' => function ($q) {
$q->orderBy('id', 'desc')->paginate(10);
}]);
return view('blog.showtags')->withTag($tag);
}
As you guys see that I move the paginate() function from find to load function which I use before for sorting post by descending order.
Now in view instead of using traditional method {!! $tag->links() !!} for making link of pagination
I use {!! $tag->paginate(10) !!}
With this line $tag = Tag::find($id)->paginate(5); You should get only one tag(or null if tag with your id dose not exist), and after that you want paginate it. If you want paginate your tags get all tags and after that paginate it Tag::paginate(5)
I am using a hasMany in my Model class to retrive the clients notes, how ever i want to order these notes by the latest date created in laravel blade template.
My code is below and im getting an error on this.
Please advice me..
#foreach($clients->notes->orderBy('created_at', 'desc') as $note)
<table class="table table-bordered">
<tr>
<td class="col-xs-2 col-md-2"><b>Created On:</b> {{ date('d/m/y', strtotime($note->created_at)) }} <b>#</b> {{ date('g:i A', strtotime($note->created_at)) }} </td>
<td class="col-xs-14 col-md-12">{{ $note->notes }}</td>
</tr>
</table>
#endforeach
Guessing, because you haven't told us what error you're getting, but:
$clients->notes is an already-fetched collection of results. $clients->notes() is a query builder that you can apply further logic like ordering or additional criteria to.
You likely want:
$clients->notes()->orderBy('created_at', 'desc')->get()
but you should do that in the controller and pass it to the view instead of having the query directly in the Blade template.
(You can alternatively use Laravel's collection functions on $clients->notes, including the sortBy() function).
Data must be ordered within controller or models. If you have used hasMany validation in model you can do as mentioned below
In model write association
public function notes()
{
return $this->hasMany('Note')->orderBy('created_at', 'desc');
}
In your controller function associate client with notes like this
$clients = Client::with('notes')->get();
Hope you get your answer
In my laravel app, I am passing a variable $data to a view which I will later include in another view. So in my controller method, I have:
public function random($id){
$data = DB::table('reports')->where('id',$id);
return view('partials.data', compact('data'));
}
In the partials.data I have:
{!! Form::open(['url'=>'reports/data',$id]) !!}
<table class="table table-responsive table-condensed table-bordered tab-content">
<thead>
<tr>
<th>Month</th>
<th>Value</th>
</tr>
</thead>
<tbody>
#foreach($data as $dat)
<tr>{{$dat->month}}</tr>
<tr>{{$dat->value}}</tr>
#endforeach
</tbody>
</table>
{!! Form::close() !!}
And in the main view I have this function:
function kpi_values(d) {
// `d` is the original data object for the row
kpi = d.id;
return '#include("reports.data", array("id" => "kpi"))';
}
Which is triggered by:
$('#monthly_table tbody').on('click', 'td.details-controls', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
row.child(kpi_values(row.data())).show();
tr.addClass('shown');
}
});
When I run this I get the following error:
ErrorException in 3534c4c98c65c2d5267bf7c54a960d41 line 13:
Undefined variable: data
I have passed the variable data in my partial view, however, it seems like it requires it in the primary view.
Is there any way of doing this without passing the variable to the primary view? I don't want to mix things because the partial view controller method requires a parameter, while the primary view has no parameters in it.
Laravel offers a great tool to handle this situation in which we need to pass some parameters to partial views without passing through the primary view. That is view composer. Here is an example :
In \App\Providers\AppServiceProvider.php file
public function boot()
{
//get data and pass it to partials.data whenever partials.data is executed
view()->composer('partials.data',function($view){
$view->with('data',DataSet::all());
});
}
For more advanced, you can learn it from Laracast
You may use share methods to pass the data to all views.
return view('partials.data')->share('data', $data);