Skip to content

CRUD and Forms

Slides

In this guide you will learn how to let users create, update and delete data. This means building forms, validations and controllers.

Laravel comes with good support for CRUD: both tooling and conventions.

In this example we start with a Laravel App with one Model already set up for CRUD: Game represents a board game. We will now create a new Model Review, and add all the CRUD features for it.

A review is written by one person about one game. So we need a 1:n relationship: one game has many reviews, each review belongs to one game.

The first steps are a recap of things you already know: models (Models and Tinker), migrations and relationships (Migrations), and factories (Testing).

With the flags -m, -f and -s artisan creates the model together with a migration, a factory and a seeder - do you remember the role of each of these files?

> php artisan make:model Review -mfs
INFO Model [app/Models/Review.php] created successfully.
INFO Factory [database/factories/ReviewFactory.php] created successfully.
INFO Migration [database/migrations/2026_11_08_222459_create_reviews_table.php] created successfully.
INFO Seeder [database/seeders/ReviewSeeder.php] created successfully.

In the new migration’s up() method:

Schema::create('reviews', function (Blueprint $table) {
$table->id();
$table->foreignId('game_id')->constrained()->cascadeOnDelete();
$table->string('author');
$table->string('title');
$table->text('text');
$table->timestamps();
});

Note the difference between string and text: string becomes a varchar(255) in the database, good for short values like a name or a title. text has no fixed length limit, so we use it for the review itself.

foreignId('game_id')->constrained()->cascadeOnDelete() creates the column, makes it a foreign key to the games table and deletes the reviews when their game is deleted by adding a constraint:

ALTER TABLE public.reviews
ADD CONSTRAINT reviews_game_id_foreign
FOREIGN KEY (game_id)
REFERENCES public.games(id)
ON DELETE CASCADE;
> php artisan migrate
INFO Running migrations.
2026_11_08_222459_create_reviews_table ................ 17.19ms DONE

The factory describes what a typical review looks like. We need it later for the tests.

In database/factories/ReviewFactory.php:

public function definition(): array
{
return [
'game_id' => Game::factory(),
'author' => fake()->name(),
'title' => fake()->sentence(4),
'text' => fake()->paragraphs(2, true),
];
}

'game_id' => Game::factory() means: if you don’t say which game the review belongs to, the factory creates a new game for it.

Be careful: this also happens with make(). Review::factory()->make() does not save the review, but it does save the new game to the database.

The seeder fills the database with some example reviews. In database/seeders/ReviewSeeder.php we look up the games by name and create reviews for them:

public function run(): void
{
$agricola = Game::where('name', 'Agricola')->firstOrFail();
$fluxx = Game::where('name', 'Fluxx')->firstOrFail();
$review = new Review;
$review->game_id = $agricola->id;
$review->author = 'Anna';
$review->title = 'Das beste Spiel auf meinem Regal';
$review->text = 'Jede Partie erzählt die Geschichte eines kleinen Bauernhofs. '
.'Man will immer alles gleichzeitig machen und hat nie genug Zeit dafür. Genial!';
$review->save();
// ... two more reviews
}

We set the properties one by one and then call save(). Review::create([...]) would be shorter, but it uses mass assignment, and the model does not allow that yet. We will come back to this when we save data from a form.

The DatabaseSeeder calls all the seeders. The order matters: the games have to exist before we can write reviews for them.

$this->call([
GameSeeder::class,
ReviewSeeder::class,
]);

Run only the new seeder:

> php artisan db:seed --class=ReviewSeeder
INFO Seeding database.
Database\Seeders\ReviewSeeder ................................ RUNNING
Database\Seeders\ReviewSeeder .............................. 35 ms DONE

or rebuild the whole database with php artisan migrate:fresh --seed.

7. Declaring the relationship on both models

Section titled “7. Declaring the relationship on both models”

The foreign key exists in the database, but Eloquent does not know about it yet. We add one method to each model.

In app/Models/Review.php:

use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Review extends Model
{
public function game(): BelongsTo
{
return $this->belongsTo(Game::class);
}
}

and in app/Models/Game.php:

use Illuminate\Database\Eloquent\Relations\HasMany;
class Game extends Model
{
public function reviews(): HasMany
{
return $this->hasMany(Review::class);
}
}

The names of the methods matter: game is singular, because a review belongs to exactly one game. reviews is plural, because a game can have many reviews. How does Eloquent know that the foreign key is called game_id?

Start php artisan tinker and turn on SQL logging (as in Models and Tinker):

> DB::listen(function ($query) { echo $query->sql . ' [' . implode(', ', $query->bindings) . "]\n";});

From the game to its reviews:

> $game = Game::where('name', 'Agricola')->first();
select * from "games" where "name" = ? limit 1 [Agricola]
> foreach ($game->reviews as $review) { echo "{$review->author}: {$review->title}\n"; }
select * from "reviews" where "reviews"."game_id" = ? and "reviews"."game_id" is not null [5]
Anna: Das beste Spiel auf meinem Regal
Ben: Lohnt jede Minute

From a review to its game:

> $review = Review::find(3);
select * from "reviews" where "reviews"."id" = ? limit 1 [3]
> $review->game->name;
select * from "games" where "games"."id" = ? limit 1 [74]
= "Fluxx"

Each relationship is loaded with one extra query, the first time you use it. Try $game->reviews->count() now: which SQL query do you see?

Before we build the web interface for reviews, we need to decide on the URLs. Laravel has a clear opinion about this, and it is based on REST.

REST (Representational State Transfer) describes the architecture of the web. You already know it from the foundations course: REST in Web Development. Here is a short version, geared towards Laravel.

In REST, the things your app is about are called resources. In our app, each game is a resource, and so is each review. REST has five principles:

  1. Every resource has its own URL. Review number 3 can be found at /reviews/3, the list of all reviews at /reviews. You can bookmark these URLs, link to them, and send them to a friend.
  2. Resources link to each other. The page of a review links to the page of its game, and back.
  3. Use the HTTP methods according to their meaning. GET reads, POST creates, PUT (or PATCH) changes, DELETE deletes. A GET request must never change any data.
  4. One resource can have different representations. Our app sends HTML to the browser. The same review could also be sent as JSON to a mobile app.
  5. Statelessness. Each request contains everything the server needs to answer it. The server stores as little as possible about the user between requests.

The four CRUD operations map to HTTP methods on URLs like this:

OperationHTTP methodURL
CreatePOST/reviews
ReadGET/reviews/3
UpdatePUT/reviews/3
DeleteDELETE/reviews/3

Notice that the URL never contains a verb: there is no /reviews/3/delete. The HTTP method says what to do, the URL says which resource.

Remember the warning at the end of the first Laravel chapter? The visit counter stored a new row in the database on every GET request. Why does that break the rules of REST? What could go wrong if a search engine or a browser preloading links visits that page?

A controller that handles all CRUD operations for one resource is called a resource controller. Artisan can create one for us:

> php artisan make:controller ReviewController --resource --model=Review --requests
INFO Request [app/Http/Requests/StoreReviewRequest.php] created successfully.
INFO Request [app/Http/Requests/UpdateReviewRequest.php] created successfully.
INFO Controller [app/Http/Controllers/ReviewController.php] created successfully.
  • --resource creates the seven methods for CRUD
  • --model=Review fills in the type Review for the parameters
  • --requests creates two extra classes for checking form data; we will need them later

The new file app/Http/Controllers/ReviewController.php contains seven empty methods:

class ReviewController extends Controller
{
public function index() { }
public function create() { }
public function store(StoreReviewRequest $request) { }
public function show(Review $review) { }
public function edit(Review $review) { }
public function update(UpdateReviewRequest $request, Review $review) { }
public function destroy(Review $review) { }
}

The names of these methods are the same in every Laravel app. Which of them have a Review as parameter, and why don’t the others?

In routes/web.php one line connects all seven methods to URLs:

use App\Http\Controllers\ReviewController;
Route::resource('reviews', ReviewController::class);

To see which routes this line created, use route:list:

> php artisan route:list --path=reviews
GET|HEAD reviews ................. reviews.index › ReviewController@index
POST reviews ................. reviews.store › ReviewController@store
GET|HEAD reviews/create ........ reviews.create › ReviewController@create
GET|HEAD reviews/{review} .......... reviews.show › ReviewController@show
PUT|PATCH reviews/{review} ...... reviews.update › ReviewController@update
DELETE reviews/{review} .... reviews.destroy › ReviewController@destroy
GET|HEAD reviews/{review}/edit ..... reviews.edit › ReviewController@edit
Showing [7] routes

{review} is a placeholder: it stands for the id of a review, like 3.

The four CRUD operations from the REST table above have become seven actions. The three extra actions are needed because a browser shows HTML pages: before you can create or edit a review, you need a page with a form.

ActionHTTP methodURLRoute nameWhat it does
indexGET/reviewsreviews.indexlist all reviews
createGET/reviews/createreviews.createshow an empty form
storePOST/reviewsreviews.storesave the data from the empty form
showGET/reviews/{review}reviews.showshow one review
editGET/reviews/{review}/editreviews.editshow a form filled with one review
updatePUT/PATCH/reviews/{review}reviews.updatesave the data from the edit form
destroyDELETE/reviews/{review}reviews.destroydelete one review

Notice that the URLs /reviews and /reviews/{review} are used several times. Laravel only knows which action to call by looking at the URL and the HTTP method.

The Game model in the example app already uses the same pattern: compare this table with php artisan route:list --path=games.

Every route in the list has a name, like reviews.index or reviews.show. In views and controllers we use the name instead of writing the URL by hand. The helper function route() turns a name into a URL:

> route('reviews.index')
= "http://localhost:8000/reviews"
> route('reviews.show', 3)
= "http://localhost:8000/reviews/3"
> route('reviews.show', Review::find(3))
= "http://localhost:8000/reviews/3"
> route('reviews.edit', 3)
= "http://localhost:8000/reviews/3/edit"

For routes with a placeholder you pass the id, or the model itself: Laravel takes the id from the model.

If you later decide that the URL should be /rezensionen instead of /reviews, you change it in routes/web.php, and all links that use route() still work.

We use this right away to add a link to the navigation in resources/views/components/layout.blade.php:

<nav>
<a href="{{ route('games.index') }}">Alle Spiele</a>
<a href="{{ route('games.create') }}">Neues Spiel</a>
<a href="{{ route('reviews.index') }}">Rezensionen</a>
</nav>

Start the app with composer run dev and click on “Rezensionen”. You get an empty white page: the route works and calls ReviewController@index, but the method does not return anything yet.

Now try /reviews/3 and /reviews/999. One of them shows an empty page, the other one shows the error “404 Not Found”. How can Laravel know that there is no review with the id 999, even though the show method is still empty?

The index action loads all reviews and hands them to a view. In app/Http/Controllers/ReviewController.php:

use Illuminate\View\View;
public function index(): View
{
$reviews = Review::with('game')->latest()->get();
return view('reviews.index', compact('reviews'));
}

latest() sorts by created_at, newest first. We will look at with('game') in a moment.

The view resources/views/reviews/index.blade.php shows the title, the author and the game of each review, with links to both:

<x-layout title="Rezensionen">
<h1>Rezensionen</h1>
<p><a href="{{ route('reviews.create') }}">Neue Rezension schreiben</a></p>
<ul class="reviews">
@foreach ($reviews as $review)
<li>
<a href="{{ route('reviews.show', $review) }}">{{ $review->title }}</a>
<span class="review-meta">
von {{ $review->author }}
zu <a href="{{ route('games.show', $review->game) }}">{{ $review->game->name }}</a>
</span>
</li>
@endforeach
</ul>
</x-layout>

Why with('game')? Let’s try the loop without it in tinker, with SQL logging turned on:

> foreach (Review::all() as $review) { echo "{$review->title} – {$review->game->name}\n"; }
select * from "reviews" []
select * from "games" where "games"."id" = ? limit 1 [5]
Das beste Spiel auf meinem Regal – Agricola
select * from "games" where "games"."id" = ? limit 1 [5]
Lohnt jede Minute – Agricola
select * from "games" where "games"."id" = ? limit 1 [74]
Chaos in der besten Form – Fluxx

One query loads the reviews, and then every $review->game sends one more query. For N reviews that is N+1 queries. This is called the N+1 problem. With three reviews you will not notice it, but with 1000 reviews the page sends 1001 queries to the database.

with('game') tells Eloquent to load the games of all reviews in advance. This is called eager loading:

> foreach (Review::with('game')->get() as $review) { echo "{$review->title} – {$review->game->name}\n"; }
select * from "reviews" []
select * from "games" where "games"."id" in (5, 74) []
Das beste Spiel auf meinem Regal – Agricola
Lohnt jede Minute – Agricola
Chaos in der besten Form – Fluxx

Two queries, no matter how many reviews there are. How many queries does each version send for 100 reviews of 10 different games?

We write tests after implementing each action. Create the test file with php artisan make:test ReviewControllerTest --pest (see Testing).

In tests/Feature/ReviewControllerTest.php:

use App\Models\Game;
use App\Models\Review;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->withoutVite();
});
test('index lists reviews with their game', function () {
$game = Game::factory()->create(['name' => 'Agricola']);
Review::factory()->for($game)->create(['title' => 'Lohnt jede Minute']);
$this->get(route('reviews.index'))
->assertOk()
->assertSee('Lohnt jede Minute')
->assertSee('Agricola');
});

Review::factory()->for($game) uses the relationship to set game_id. withoutVite() lets the tests run without building the CSS and JavaScript first.

The show action is short:

public function show(Review $review): View
{
return view('reviews.show', compact('review'));
}

and the view resources/views/reviews/show.blade.php:

<x-layout :title="$review->title">
<h1>{{ $review->title }}</h1>
<p class="review-meta">
Rezension von {{ $review->author }}
zu <a href="{{ route('games.show', $review->game) }}">{{ $review->game->name }}</a>
</p>
<p class="review-text">{{ $review->text }}</p>
</x-layout>

But wait: where does $review come from? Nobody calls Review::find(). To understand this, we need two new concepts: dependency injection and route model binding.

Look at the parameters of the controller methods: show(Review $review), store(StoreReviewRequest $request). We never call these methods ourselves. Laravel calls them, and Laravel decides which arguments to pass.

To do this, Laravel looks at the type of each parameter and creates a fitting object. This is called dependency injection: the method declares what it depends on, and the framework “injects” it from the outside.

You have already used this in the first Laravel chapter:

public function index(Request $request, ConnectionInterface $db): View

You did not create the Request object or open the database connection. You only wrote down the types, and Laravel handed over the right objects.

The part of Laravel that knows how to create all these objects is called the service container. It knows that a Request is the current HTTP request, and that a ConnectionInterface is the database connection configured in .env. In a test, the service container can hand out different objects, for example a fake mail server instead of a real one.

The order and the names of the parameters do not matter, only the types.

For models, dependency injection has a special feature called route model binding. Laravel sees that

  • the route reviews/{review} has a placeholder called review, and
  • the method show(Review $review) has a parameter called $review of type Review.

So Laravel takes the value from the URL, for example 3, and runs Review::findOrFail(3). If there is no review with this id, findOrFail stops with “404 Not Found”, and show is never called.

This answers the question from above: /reviews/999 showed a 404 page even though show was still empty.

Two more tests:

test('show displays one review', function () {
$review = Review::factory()->create([
'author' => 'Anna',
'title' => 'Das beste Spiel',
'text' => 'Genial!',
]);
$this->get(route('reviews.show', $review))
->assertOk()
->assertSee('Das beste Spiel')
->assertSee('Anna')
->assertSee('Genial!')
->assertSee($review->game->name);
});
test('show returns 404 for a review that does not exist', function () {
$this->get('/reviews/999')->assertNotFound();
});

What would happen if you renamed the parameter to show(Review $r)?

Creating a review takes two actions: create shows the empty form, store saves the data the form sends back.

The form needs a list of all games for a <select>, so create loads them:

use App\Models\Game;
public function create(): View
{
$games = Game::orderBy('name')->get();
return view('reviews.create', compact('games'));
}

The view resources/views/reviews/create.blade.php:

<x-layout title="Neue Rezension">
<h1>Neue Rezension</h1>
<form method="POST" action="{{ route('reviews.store') }}" class="review-form">
<label for="game_id">Spiel</label>
<select id="game_id" name="game_id" required>
<option value="">– bitte wählen –</option>
@foreach ($games as $game)
<option value="{{ $game->id }}">{{ $game->name }}</option>
@endforeach
</select>
<label for="author">Dein Name</label>
<input id="author" name="author" required>
<label for="title">Titel</label>
<input id="title" name="title" required>
<label for="text">Text</label>
<textarea id="text" name="text" rows="8" required></textarea>
<button type="submit">Speichern</button>
</form>
</x-layout>

Compare the form with the table of the seven actions: the form is sent with POST to /reviews, which is the store action. The name attributes of the fields are the names of the columns in the database. The <select> shows the name of each game, but sends its id.

Fill out the form and press “Speichern”. Instead of saving, Laravel shows:

419 | Page Expired

Laravel rejects every POST, PUT, PATCH and DELETE request that does not carry a secret token. This protects against Cross-Site Request Forgery (CSRF): another website could contain a form that sends a request to your app. If you are logged in to your app, your browser sends your session cookie along, and the request looks like it came from you.

The token proves that the form was really created by your app. Add @csrf as the first line inside every form:

<form method="POST" action="{{ route('reviews.store') }}" class="review-form">
@csrf
...

Look at the HTML source of the page: what did @csrf turn into?

Now the request reaches store. A first attempt:

use Illuminate\Http\Request;
public function store(Request $request)
{
Review::create($request->all());
}

$request->all() returns all form fields as an array: ['_token' => '...', 'game_id' => '5', 'author' => 'Dana', ...]. This gives an error:

Illuminate\Database\Eloquent\MassAssignmentException
Add [game_id] to fillable property to allow mass assignment on [App\Models\Review].

You know this from Models and Tinker: create() uses mass assignment, and the model only accepts the attributes listed in $fillable. In app/Models/Review.php:

protected $fillable = [
'game_id',
'author',
'title',
'text',
];

Now it is clear why this protection exists: the data comes from a form, and anyone can add more fields to a form with the browser’s developer tools. Without $fillable, a user could send id or created_at and change them.

The fields have the HTML attribute required, so the browser does not send an empty form. But the browser is not under our control: the developer tools can remove required, and a script can send any data.

What happens if the title is missing? The database refuses to save the row:

Illuminate\Database\QueryException
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "title"
of relation "reviews" violates not-null constraint

And if game_id points to a game that does not exist, the foreign key stops it:

Illuminate\Database\QueryException
SQLSTATE[23503]: Foreign key violation: 7 ERROR: insert or update on table "reviews"
violates foreign key constraint "reviews_game_id_foreign"
DETAIL: Key (game_id)=(9999) is not present in table "games".

The database protects the data, which is good. But the user only sees “500 Server Error” and loses everything they typed. We need to check the data before saving, and tell the user what is wrong.

This is what the class StoreReviewRequest is for, which artisan created together with the controller. It is a Form Request: a request object that knows the rules for its data.

The generated class has two methods. The first is authorize(), which returns false. If we use the class as it is, every form is rejected with:

403 | This action is unauthorized.

authorize() decides who may send this form. Everybody may write a review, so we return true. (In the chapter on authentication we will come back to this.)

The second method, rules(), returns the validation rules for each field. In app/Http/Requests/StoreReviewRequest.php:

public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'game_id' => ['required', 'exists:games,id'],
'author' => ['required', 'string', 'max:255'],
'title' => ['required', 'string', 'max:255'],
'text' => ['required', 'string'],
];
}
  • required: the field must not be empty
  • exists:games,id: there must be a row in the table games with this id
  • max:255: not longer than the string column in the database

Now change the parameter type of store from Request to StoreReviewRequest:

use App\Http\Requests\StoreReviewRequest;
public function store(StoreReviewRequest $request)
{
Review::create($request->validated());
}

This is dependency injection again: Laravel sees the type StoreReviewRequest, creates the object, and runs the validation before store is called. If the data is not valid, store is never called. So inside store we can be sure the data is correct.

$request->validated() returns only the fields that have a rule, so _token and any extra fields are left out.

What happens when the validation fails? Laravel sends a redirect back to the form:

HTTP/1.1 302 Found
Location: http://localhost:8000/reviews/create

Before redirecting, Laravel stores two things in the session: the error messages and the data the user typed. The form can use both. For the title field:

<label for="title">Titel</label>
<input id="title" name="title" value="{{ old('title') }}" required>
@error('title') <p class="error">{{ $message }}</p> @enderror
  • old('title') returns what the user typed before the redirect, so nothing is lost
  • @error('title') ... @enderror is only shown if there is an error for this field, and $message contains the message

For a <select>, old() decides which option is selected:

<option value="{{ $game->id }}" @selected(old('game_id') == $game->id)>

Sending a form with an empty title and game_id 9999 now shows:

The selected game id is invalid.
The title field is required.

The messages are in English, because the app is configured for English. In the chapter on internationalization you will see how to translate them.

All errors are also available in the variable $errors, for example @if ($errors->any()) to show a message at the top of the form.

After saving, store should not show a page itself. Instead it sends a redirect to the new review:

use Illuminate\Http\RedirectResponse;
public function store(StoreReviewRequest $request): RedirectResponse
{
$review = Review::create($request->validated());
return redirect()->route('reviews.show', $review)
->with('status', 'Die Rezension wurde gespeichert.');
}

This pattern is called Post/Redirect/Get: the browser sends a POST, receives a redirect, and then loads the new page with GET. If the user reloads the page now, the browser only repeats the harmless GET.

with('status', ...) stores a message in the session for exactly one more request. This is called a flash message. The layout already shows it:

@if (session('status'))
<p class="status">{{ session('status') }}</p>
@endif

What would happen if store showed a page directly and the user pressed reload?

/**
* @return array<string, mixed>
*/
function validReviewData(array $overrides = []): array
{
return [
'game_id' => Game::factory()->create()->id,
'author' => 'Dana',
'title' => 'Ein tolles Spiel',
'text' => 'Wir haben es fünfmal hintereinander gespielt.',
...$overrides,
];
}
test('store saves a review and redirects to it', function () {
$response = $this->post(route('reviews.store'), validReviewData());
$review = Review::where('title', 'Ein tolles Spiel')->firstOrFail();
$response->assertRedirect(route('reviews.show', $review))
->assertSessionHas('status');
expect($review->author)->toBe('Dana');
});
test('store rejects a review without a title', function () {
$this->post(route('reviews.store'), validReviewData(['title' => '']))
->assertSessionHasErrors('title');
expect(Review::count())->toBe(0);
});
test('store rejects a game that does not exist', function () {
$this->post(route('reviews.store'), validReviewData(['game_id' => 999]))
->assertSessionHasErrors('game_id');
});

The helper function validReviewData() returns valid data, and each test overrides just the field it is about. Notice that the tests do not need a CSRF token: Laravel turns the CSRF check off when running tests.

Editing also takes two actions: edit shows the form filled with the current data, update saves the changes.

public function edit(Review $review): View
{
$games = Game::orderBy('name')->get();
return view('reviews.edit', compact('review', 'games'));
}

The edit form needs the same fields as the create form. The only difference: each field shows the current value. For the title:

<input id="title" name="title" value="{{ old('title', $review->title) }}" required>

The second argument of old() is the default value: if the user did not just send the form, it shows the value from the database.

Instead of copying all fields, we move them into their own file resources/views/reviews/_form.blade.php. The underscore at the beginning of the name is a convention: this file is not a complete page, only a part of one.

<label for="game_id">Spiel</label>
<select id="game_id" name="game_id" required>
<option value="">– bitte wählen –</option>
@foreach ($games as $game)
<option value="{{ $game->id }}" @selected(old('game_id', $review->game_id) == $game->id)>
{{ $game->name }}
</option>
@endforeach
</select>
@error('game_id') <p class="error">{{ $message }}</p> @enderror
<label for="author">Dein Name</label>
<input id="author" name="author" value="{{ old('author', $review->author) }}" required>
@error('author') <p class="error">{{ $message }}</p> @enderror
<label for="title">Titel</label>
<input id="title" name="title" value="{{ old('title', $review->title) }}" required>
@error('title') <p class="error">{{ $message }}</p> @enderror
<label for="text">Text</label>
<textarea id="text" name="text" rows="8" required>{{ old('text', $review->text) }}</textarea>
@error('text') <p class="error">{{ $message }}</p> @enderror

Both forms include it with @include. resources/views/reviews/create.blade.php:

<form method="POST" action="{{ route('reviews.store') }}" class="review-form">
@csrf
@include('reviews._form')
<button type="submit">Speichern</button>
</form>

The partial uses $review, so the create action now also has to pass one. An empty new Review works: all its attributes are null.

public function create(): View
{
$review = new Review;
$games = Game::orderBy('name')->get();
return view('reviews.create', compact('review', 'games'));
}

The Game model in the starter app uses the same pattern: compare with resources/views/games/_form.blade.php.

According to the table of actions, the edit form has to be sent with PUT to /reviews/{review}. But HTML forms only know two methods: GET and POST. If we send the form with POST, Laravel answers:

405 | Method Not Allowed
The POST method is not supported for route reviews/3.
Supported methods: GET, HEAD, PUT, PATCH, DELETE.

The trick is called method spoofing: the form is sent with POST, and a hidden field named _method tells Laravel which method was meant. @method('PUT') creates this hidden field. resources/views/reviews/edit.blade.php:

<x-layout title="Rezension bearbeiten">
<h1>Rezension bearbeiten</h1>
<form method="POST" action="{{ route('reviews.update', $review) }}" class="review-form">
@csrf
@method('PUT')
@include('reviews._form')
<button type="submit">Speichern</button>
</form>
</x-layout>

The rules for changing a review are the same as for creating one. So UpdateReviewRequest inherits everything from StoreReviewRequest. In app/Http/Requests/UpdateReviewRequest.php:

class UpdateReviewRequest extends StoreReviewRequest
{
//
}

The update action gets two objects by dependency injection: the validated request and the review from the URL:

public function update(UpdateReviewRequest $request, Review $review): RedirectResponse
{
$review->update($request->validated());
return redirect()->route('reviews.show', $review)
->with('status', 'Die Rezension wurde geändert.');
}

update() uses mass assignment too, so it also depends on $fillable.

The tests:

test('edit shows the form with the current values', function () {
$review = Review::factory()->create(['title' => 'Alter Titel']);
$this->get(route('reviews.edit', $review))
->assertOk()
->assertSee('value="Alter Titel"', escape: false);
});
test('update saves the changes', function () {
$review = Review::factory()->create();
$this->put(route('reviews.update', $review), validReviewData(['title' => 'Neuer Titel']))
->assertRedirect(route('reviews.show', $review));
expect($review->fresh()->title)->toBe('Neuer Titel');
});
test('update rejects an empty text', function () {
$review = Review::factory()->create(['text' => 'Alter Text']);
$this->put(route('reviews.update', $review), validReviewData(['text' => '']))
->assertSessionHasErrors('text');
expect($review->fresh()->text)->toBe('Alter Text');
});

The last action is destroy:

public function destroy(Review $review): RedirectResponse
{
$review->delete();
return redirect()->route('reviews.index')
->with('status', 'Die Rezension wurde gelöscht.');
}

To call it, we need a DELETE request. A link can only send GET, so the delete button is a small form, again with method spoofing. We add it to the show view, next to a link to the edit form:

<div class="actions">
<a href="{{ route('reviews.edit', $review) }}">Bearbeiten</a>
<form method="POST" action="{{ route('reviews.destroy', $review) }}">
@csrf
@method('DELETE')
<button type="submit">Löschen</button>
</form>
</div>

Why not just a link to /reviews/3/delete? Think back to the REST rules: a GET request must never change data. Search engines, browsers that preload links and link previews in chat apps all send GET requests by themselves. A delete link would be clicked by machines.

test('destroy deletes the review', function () {
$review = Review::factory()->create();
$this->delete(route('reviews.destroy', $review))
->assertRedirect(route('reviews.index'));
expect(Review::find($review->id))->toBeNull();
});

REST says resources should link to each other. A review already links to its game. Now the page of a game should list its reviews and offer to write a new one. In resources/views/games/show.blade.php:

<h2>Rezensionen</h2>
@if ($game->reviews->isEmpty())
<p>Noch keine Rezensionen.</p>
@else
<ul class="reviews">
@foreach ($game->reviews as $review)
<li>
<a href="{{ route('reviews.show', $review) }}">{{ $review->title }}</a>
<span class="review-meta">von {{ $review->author }}</span>
</li>
@endforeach
</ul>
@endif
<p><a href="{{ route('reviews.create', ['game_id' => $game->id]) }}">Rezension schreiben</a></p>

route() adds values that are not placeholders of the route as query parameters. For Agricola the link becomes /reviews/create?game_id=5.

The create action reads this query parameter and preselects the game. It gets the request by dependency injection, just like in chapter 1:

use Illuminate\Http\Request;
public function create(Request $request): View
{
$review = new Review(['game_id' => $request->query('game_id')]);
$games = Game::orderBy('name')->get();
return view('reviews.create', compact('review', 'games'));
}

The form already uses old('game_id', $review->game_id), so the game is selected.

Remember cascadeOnDelete() in the migration? Delete a game that has reviews, and its reviews are gone too. A test proves it:

test('deleting a game deletes its reviews', function () {
$review = Review::factory()->create();
$this->delete(route('games.destroy', $review->game));
expect(Review::find($review->id))->toBeNull();
});

Artisan created a lot of the code for us. Here is what we wrote ourselves:

FileGenerated by artisanWritten by us
app/Models/Review.phpthe empty class$fillable, game()
app/Models/Game.php–reviews()
migrationid(), timestamps()the columns and the foreign key
ReviewFactory, ReviewSeederempty classesthe example data
routes/web.php–Route::resource(...)
ReviewControllerseven empty methods with parametersthe body of each method
StoreReviewRequestauthorize() and empty rules()true and the rules
UpdateReviewRequesta copy of StoreReviewRequestinherit from StoreReviewRequest
views–index, show, create, edit, _form
ReviewControllerTestan example testthe tests for all actions

New concepts in this chapter:

  • REST and resources: one URL per resource, HTTP methods with their meaning
  • resource controller and resource route: seven actions with fixed names
  • named routes and the route() helper
  • N+1 problem and eager loading with with()
  • dependency injection, the service container and route model binding
  • CSRF protection with @csrf
  • Form Requests for validation, old() and @error for showing errors
  • Post/Redirect/Get and flash messages
  • method spoofing with @method

Which request does Laravel send to ReviewController@update?

  • GET /reviews/3/edit
  • POST /reviews/3/update
  • PUT /reviews/3
  • POST /reviews

A page lists 50 reviews and shows the name of the game for each, using Review::all(). How many queries does it send?

  • 1
  • 2
  • 51
  • 100

The route is reviews/{review}, the method is show(Review $review). What happens for /reviews/999 if there is no review 999?

  • $review is null
  • $review is a new, empty review
  • Laravel answers with 404 Not Found, and show is not called
  • The database throws a QueryException

How does Laravel decide what to pass to store(StoreReviewRequest $request)?

  • By the name of the parameter $request
  • By the type StoreReviewRequest of the parameter
  • By the order of the parameters
  • From the action attribute of the form

A form without @csrf is sent. What does Laravel answer?

  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 419 Page Expired

The validation in StoreReviewRequest fails. What happens?

  • store is called, and $request->validated() is empty
  • Laravel redirects back to the form and stores the errors and the old input in the session
  • Laravel shows a 500 error page
  • The browser shows the errors without sending the form

Why does the edit form contain @method('PUT')?

  • Because PUT is faster than POST
  • Because HTML forms can only send GET and POST
  • Because otherwise the CSRF token is missing
  • Because update only works with JSON

Why is “Löschen” a button in a form and not a link?

  • Links cannot point to a controller action
  • Buttons look better
  • A link sends GET, and GET must never change data
  • Links cannot contain an id