0
0
Laravelframework~30 mins

Mass assignment protection in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Mass Assignment Protection in Laravel
📖 Scenario: You are building a simple Laravel application to manage a list of books. Each book has a title, author, and price. You want to safely create new book records from user input without accidentally allowing unwanted fields to be set.
🎯 Goal: Learn how to protect your Laravel model from mass assignment vulnerabilities by specifying which fields can be filled using mass assignment.
📋 What You'll Learn
Create a Laravel model called Book with the fields title, author, and price.
Add a $fillable property to the Book model to allow mass assignment only on title and author.
Write code to create a new Book instance using mass assignment with an array containing title, author, and price.
Ensure that the price field is not set by mass assignment and remains null or default.
💡 Why This Matters
🌍 Real World
Mass assignment protection is essential in Laravel applications to prevent users from setting sensitive or unintended model fields when submitting forms or API requests.
💼 Career
Understanding mass assignment protection helps you write secure Laravel code, a key skill for backend web developers working with PHP frameworks.
Progress0 / 4 steps
1
Create the Book model with fields
Create a Laravel model class called Book that extends Model. Add the protected properties title, author, and price as fillable fields later. For now, just define the class with no fillable property.
Laravel
Need a hint?

Start by creating a class named Book inside the App\Models namespace that extends Laravel's Model class.

2
Add the $fillable property to allow mass assignment
Inside the Book model class, add a protected property called $fillable and set it to an array containing the strings 'title' and 'author' only.
Laravel
Need a hint?

The $fillable array tells Laravel which fields can be set using mass assignment. Only include 'title' and 'author'.

3
Create a new Book instance using mass assignment
Write code to create a new Book instance using mass assignment with an array containing 'title' => 'The Great Gatsby', 'author' => 'F. Scott Fitzgerald', and 'price' => 20. Assign this instance to a variable called $book.
Laravel
Need a hint?

Use the new Book([...]) syntax with an array to set the fields. Include title, author, and price keys.

4
Verify mass assignment protection on the price field
Add code to check that the price property of the $book instance is not set by mass assignment. Assign null to $priceValue if $book->price is not set or is null, otherwise assign $book->price.
Laravel
Need a hint?

Use the null coalescing operator ?? to assign null if $book->price is not set.