Abdou
Abdou

Reputation: 37

404 not found when storing data laravel 8

when i click on the submit button it returns the route with 404 page

this is the blade

<form method="POST" action="{{ route('comment.store') }}" >
      @csrf
     <input type="text">
     <button type="submit">Add comment</button>
</form>

the comment controller:

    class CommentController extends Controller
{
    public function __construct() {
        $this->middleware('auth');
    }


    public function store(Request $request)
    {
        $film = Film::findOrFail($request->film_id);

        Comment::create([
            'comment' => $request->comment,
            'user_id' => Auth::id(),
            'post_id' => $film->id
        ]);
        return redirect()->route('showFilm', $film->id);
    }
}

and this is my web.php:

Route::post('comment/store', [CommentController::class, 'store'])->name('comment.store');

Upvotes: 0

Views: 719

Answers (2)

Jarliev P&#233;rez
Jarliev P&#233;rez

Reputation: 263

This happens because you're using findOrFail() method, which, as it's name implies, will return your model if it's found, otherwise, will you show you a 404 page. You should validate film_id in the store method

Edit: Add a hidden input with your film_id in your view

           <form method="POST" action="{{ route('comment.store') }}" >
            @csrf
            <input type="hidden" name="film_id" value="{{ $film->id }}">
            <div class="form">
                <input type="text" placeholder="Add comment..">
                <button type="submit" class="submit">Add comment</button>
               </div>
           </form>

that way, film_id will be sent to your controller

Upvotes: 1

STA
STA

Reputation: 34708

Your findOrFail() method return this 404 error, cause $request->film_id is null

Upvotes: 1

Related Questions