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'));
}
Related
I am working on a web programing assignment for University and have hit a snag when trying to make a like and dislike function for a comments area of a guestbook.
Evectively the numbers on the site should update by one once either the dislike or like button is pressed.
My comments display correctly however the liking function is broken and I have no idea how to fix it.
Here is my code
Controller (LikesController.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LikesController extends Controller (It says my Like Controller is never used not sure why this is)
{
public function likepl (Comment, $comment) { (Says that Comment is "Undefined" also not sure why this is)
$comment -> likePlus (); (Method likePlus not found)
return redirect () -> action ('CommentController#index');
}
}
Model (comment.php)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public static function paginate(int $COMMENTS_PER_PAGE)
{
}
public function likePlus()
{
$this -> likes += 1;
$this -> update ();
}
public function dislikePlus()
{
$this -> dislikes += 1;
$this -> update ();
}
}
View Page (comment.comments)
#extends('setup')
#section('content')
<div class="container main-table">
<div class="box">
<h1 class="title">Guest book Comments</h1>
#if (count ($comments) > 5)
<table class="table is-striped is-hoverable">
<thead>
<tr>
<th>User</th>
<th>Comment</th>
<th>Date</th>
<th>Likes</th>
<th>DisLikes</th>
</tr>
</thead>
<tr>
#foreach ($comments as $c)
{{--declaring the comments--}}
<tr>
<td>{{ $c -> user }}</td>
<td>{{ $c -> comments }}</td>
<td>{{ $c -> created_at -> format ('D jS F') }}</td>
<td>{{ $c -> likes }}</td>
<td>{{ $c -> dislikes }}</td>
</tr>
<tr class="icon heart">
<td><a class="button" href="/comment/{{ $c -> id }}/like/"><ion-icon name="md-heart"></ion-icon></a></td>
<td><a class="button" href="/comment/{{ $c -> id }}/dislike/"><ion-icon name="md-heart-empty"></ion-icon></a></td>
</tr>
#endforeach
</table>
{{ $comments -> links() }} {{-- Setting pagination--}}
#else
<div class="notification is-info">
<p>
The Guest book is empty. Why not add a comment?
</p>
</div>
#endif
</div>
</div>
#endsection
I have annotated the code with the visible errors that I get as for better refference.
Here are the Routes that I am using for the comments page.
Route::get('/','CommentController#index');
Route::get('/comment/{comment}/like/', 'LikesController#likePl');
Route::get('/comment/{comment}/dislike/', 'DislikesController#dislikePl');
The update() function does not work the way you are using it. You either update the property and use the save() function, or you pass an array to the update function.
// 1.
$this->likes += 1;
$this->save();
// 2.
$this->update([
'likes' => $this->likes + 1,
]);
Update: Even better would be to use the built-in increment() function:
$this->increment('likes');
This way there is no need to know the number of likes beforehand.
Can we please work on the following first.
LikePl function name should match the name on the router (action#method)
The method inside the controller accept request like so
public function likePl (Request $request) { //code here }
Methods inside the Model are accessed using their namespace like so
App\Comment::likePlus() or you can import the namespace like "use App\Comment" there after inside the method just simply do "Comment::likePlus()".
Please refer here Laravel models for more information.
Fixing this will remove the errors you currently have. Use "dd($request->all())" inside your likePl method to check if you are getting the values you expect.
Hope this help a bit...
I have added Datatables in my application and i wanted to make the ID of each entry to be a hyperlink to the edit page in order for a user to be able to edit their Post. But i am getting a 404 Not Found error
I tried updating my route file but i don't get the correct result and i cannot figure what i am doing wrong
My web php file has:
Route::get('edit','PostsController#edit');
The index for my posts is
<table class="display" id="postsTable">
<thead>
<tr>
<td>ID</td>
<th>Title</th>
<th>Slug</th>
<th>Subtitle</th>
<th>Content</th>
<th>Category</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
And the PostsController edit function is:
public function edit($id)
{
$posts = Post::findOrFail($id);
return view('posts.edit',compact('posts'));
}
I tried searching online and playing a bit with my routes but i managed to make things worse rather than solving my issue. any help is much appreciated!
You can set Route name like below
Route::get('edit/{id}','PostsController#edit')->name('edit_post');
Then in HTML section use it like below
<tbody>
#foreach($posts as $post)
<tr>
<td>Edit Post</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
You should add some validation on client side to be sure that you have data so you can add your code inside if condition like below
#if ($posts ?? count($posts) ?? false)
// Your code here
#endif
Are you sure there is a record in your database that matches the $id that came with the get method? If there is no matching record, findOrFail($id) returns 404 pages.
In your controller check, the posts are found or not
public function edit($id)
{
$posts = Post::findOrFail($id);
// check post are found or not
if(!isset($posts)){
# show your errors if data not found
}
return view('posts.edit',compact('posts'));
}
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);