Andreas Panteli
Andreas Panteli

Reputation: 47

Laravel 5.8 Editing a Post results in 404 error

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><a href="edit/{{$post->id}}">{{$post->id}}</a></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!

Upvotes: 0

Views: 261

Answers (3)

Vikas Ukani
Vikas Ukani

Reputation: 105

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

Upvotes: 0

Waleed
Waleed

Reputation: 39

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><a href="{{ route('edit_post', $post->id) }}">Edit Post</a></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

Upvotes: 1

Mustafa Altuntas
Mustafa Altuntas

Reputation: 1

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.

Upvotes: 0

Related Questions