Exploring New Eloquent, Testing, and Array Helpers in Laravel 12.4
Overview
Model::except(), assertThrowsNothing, and Arr::sole(), developers can write more expressive code with less boilerplate.
Prerequisites
To get the most out of this tutorial, you should have a solid grasp of Arr helper class, and the
Key Libraries & Tools
- Laravel 12.4 Framework: The core environment providing these new features.
- Eloquent ORM: The database abstraction layer where the new
except()method lives. - Laravel Testing: The integrated suite containing the updated exception assertions.
Code Walkthrough
Model Visibility with except()
Previously, we used makeHidden() to hide attributes on a model instance. The new except() method offers a more intuitive syntax for returning all attributes except a specific few.
$user = User::first();
// Returns all attributes EXCEPT email and name
return $user->except(['email', 'name']);
This method mirrors the behavior of the only() method but works as its logical inverse, making dynamic attribute filtering much cleaner during API development.
Verifying Code Safety with assertThrowsNothing
Testing that code fails correctly is easy with assertThrows(), but ensuring code never fails often resulted in implicit tests. assertThrowsNothing to make this explicit.
$this->assertThrowsNothing(function () {
(new ImportUsersAction)->handle();
});
If any exception bubbles up during execution, the test fails immediately and provides a clear error message identifying the unexpected exception type.
Strict Array Checks with Arr::sole()
While the sole(), we now have a dedicated helper for standard arrays. This ensures an array contains exactly one element.
use Illuminate\Support\Arr;
$data = ['name' => 'Christoph'];
$result = Arr::sole($data);
// This will throw a MultipleRecordsFoundException if more than one item exists
Syntax Notes
Notice the consistency in except() method on models now aligns with the except() method found in the Request and Collection classes. Similarly, Arr::sole() brings parity between database queries and raw data manipulation.
Practical Examples
- Privacy Filters: Use
except(['ssn', 'password'])when logging model state to ensure sensitive data stays out of logs. - Refactoring Tests: Replace empty tests that rely on "no news is good news" with
assertThrowsNothingto document intent clearly.
Tips & Gotchas
Avoid confusing Model::except() with database-level select(). The except() method works on a model instance that has already been retrieved; it does not filter the SQL query itself. For large datasets, always filter at the query level to save memory.
