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);
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'));
}
I am trying to get the total of the column Price with condition BillPaid column value should be 0.
My code block is
public function countDue()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price')
->get();
return response()->json($getTotalDue);
return compact('getTotalDue');
}
controller code block for calling the countDue method.
public function create()
{
return view('pages.booksin', $this->countDue());
}
view page
<table id="showBooksIn" class="table table-bordered gridview">
<thead>
<tr><th>Total Due Amount</th></tr>
</thead>
<tbody>
#if(isset($getTotalDue))
#foreach($getTotalDue as $data)
<tr>
<td> {{$data}} </td>
</tr>
#endforeach
#endif
</tbody>
</table>
but I am getting error as :
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to a member function get() on float
My table structure is:
From Laravel's documentation, you don't need to chain the get() method there.
public function countDue(){
$getTotalDue = DB::table('ordered_books')->where('BillPaid', 0)->sum('Price'); //Get the sum using the Laravel's query builder aggregate sum method
return $getTotalDue;
}
public function create()
{
return view('pages.booksin', ['getTotalDue' => $this->countDue()]); //Pass the `countDue()` method output to the view
}
Note
This is a single value, you might want to display it inside a header or paragraph element like so:
#if(isset($getTotalDue))
<h2>{{ $getTotalDue }}</h2>
#endif
You don't need the get() method in there.
public function countDue()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
return response()->json($getTotalDue);
return compact('getTotalDue');
}
Also, you have two return statements right after another, making the second one unreachable.
The second argument of the view() method needs to be an array, or you could use the with() syntax. You should try the following code, and passing the $getTotalDue into the view.
public function create()
{
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
return view('pages.booksin')->with(['getTotalDue' => $getTotalDue]);
}
No need to use get()
$getTotalDue = DB::table('ordered_books')
->where('BillPaid', 0)
->sum('Price');
will return a float with your sum value
I'm working on updating a laravel blade template to insert some database info into an html table. IN order to do this, I'm having to add new data to the controller for this blade and that's where I'm having some troubles.
I'm still trying to understand more with laravel, so I'm thinking my syntax or methods of creating this data are incorrect but I just can't put my finger on it right now.
In my function below, the $calls_allowed portion was already existing and it works on the page currently. I created the $contact_events portion of the function and that's where my problem is.
IN my view, I created a foreach loop and if statement around the html table in question. The table loads, but it's empty even though there are records in the database for the dealer.
I'm trying to say
if $dealer-> id matches contact_events.dealer_num, load all records for that dealer
contact_events is the table and dealer_num is the column I'm matching, then I'm trying to load the columns from that table (updated_at,method,notes) into the html table.
The affected code is below. The view/route/controller work, it's just this function I'm creating that isn't loading data. Any help is much appreciated.
Controller code:
public function show($id)
{
$d = Dealer::find($id);
if(!$d){
\Session::flash('warning_message', 'Sorry that resource can not be found.');
return redirect()->route('account.dealer.index');
}
$calls_allowed = DB::table('dealers.dealers')->
where('dealer_num', $id)->
pluck('calls_allowed');
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
if(!empty($calls_allowed)){
$d->calls_allowed = $calls_allowed[0];
} else {
$d->calls_allowed = null;
}
return view('Account.Dealer.show')->with('dealer', $d);
}
View code:
<thead>
<tr>
<th>Contacted Date</th>
<th>Type of Contact</th>
<th>Call Notes</th>
</tr>
</thead>
#foreach($dealer->contact_events as $events)
#if($events->dealer_num = $dealer->id)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endif
#endForeach
It looks like you are not assigning the data to the object after retrieving from database.
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
// add this
$d->contact_events = $contact_events;
This seems like a perfect time to use the power of Laravel's Eloquent ORM...
Check out the with and has in the Laravel docs
This will require some finessing based on your needs, but it will be something like this:
$d = Dealer::where('id', '=', $id)
->with('contact_events')->first();
This uses Eloquent to get all of the contact_events that belong to the dealer with the $id.
Then you can do something like this
note: this assumes that calls_allowed is a record on the dealer table. if I misunderstood that, you can still run than you can include that just as you have it.
#if(!is_null($dealer->calls_allowed)
#foreach($dealer->contact_events as $events)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endForeach
#endif
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 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