Laravel 5.8 Editing a Post results in 404 error - php

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'));
}

Related

View not recieving variable from controller Laravel 8

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'));
}

Understanding Laravel's Pagination

I'm trying to wrap my head around pagination based on what I've read.
I've never done pagination before so excuse my lack of knowledge. Based on the documentation, I do not see how to get the next page's data. I'm using a client-side (js) library.
Backend Model:
return User::where('col', $value)->paginate(15);
The above gave me this json.
Based on the data available: from, last_page etc, what should I pass to the backend to get, say, page 2? From the json I can get page 2 but how to query for page 2? Something like this would make sense:
return User::where('col', $value)->paginate(15)->nextPage(2);
My understanding of paginate is so show the amount of items per page.
Doing this in raw sql is doable:
LIMIT 10 OFFSET 15
To elaborate, here's my controller:
public function all()
{
$customers = ( new Customer )->getCustomers();
if ($customers) {
return response()->json($customers, 200);
}
return response()->json([], 200);
}
You can paginate resources using laravels default pagination inputs.
You don't have to do ->nextPage() or something just send page input and laravel will handle rest of it.
like this;
http://example.com/posts?page=2;
I aggree, Laravel Pagination Docs is not beginner friendly.
Hi you could configure like this:
$users = Users::all()->paginate(5);
return view('users.index',compact('users'))
->with('i', (request()->input('page', 1) - 1) * 5);
This will return 5 records per page. Configure by your needs.
In you index file, do something like:
<table class="table table-bordered">
<tr>
<th>no</th>
<th>user id</th>
<th>Name</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $user->user_id }}</td>
<td>{{ $user->name }}</td>
#endforeach
</table>
{!! $users->links() !!}

Creating function for laravel controller/view to load database values

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

How to use pagination along with laravel eloquent find method in laravel 5.4

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)

How to order my foreach in laravel blade

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

Categories