Challenge 1: Write Inline Validation — Possible Solution ==================================================================== // app/Http/Controllers/AuthorController.php use App\Models\Author; use Illuminate\Http\Request; public function store(Request $request) { $validated = $request->validate([ 'name' => 'required|string|max:100', 'bio' => 'nullable|string', ]); $author = Author::create($validated); return redirect()->route('authors.show', $author); }
WHY THIS WORKS -------------- - 'name' => 'required|string|max:100' enforces three rules at once via the pipe-separated string syntax: the field must be present, must be a string, and must not exceed 100 characters — a request missing "name" entirely, or submitting one 200 characters long, both fail validation automatically. - 'bio' => 'nullable|string' allows bio to be omitted or empty (nullable) while still requiring it to be a string IF it is present — without nullable, an empty bio field would fail the implicit "required" rules don't have by default, but omitting it entirely is what nullable explicitly permits. - $request->validate([...]) either returns the validated data (as $validated here) or automatically redirects back with errors and old input flashed to the session — there's no explicit if/else branching needed the way Django's Form.is_valid() requires, because a failed validation never lets execution reach the line after validate() at all. - Author::create($validated) only receives the two validated fields — name and bio — matching Author's own $fillable array from Chapter 5, the same two-layer defense (validation + $fillable) the chapter describes.