Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Four Essential Laravel Best Practices for Beginners

Laravel gives PHP developers built-in tools to handle web requests, talk to databases, and test applications. Its database layer, Eloquent, maps database rows to PHP models so your code can read and update records as objects. If you are new to the framework, you can avoid a lot of common bugs by building four habits early: check both user permissions and incoming data, load related database records up front, track schema changes and group related writes, and test the behavior your users see.

The documentation links below point to Laravel 13.x. Before you copy version-specific syntax or features, check the docs for the Laravel version installed in your project.

1. Validate input, check permissions, and save only validated fields

Treat every value a browser sends as untrusted. Before you touch the database, run two checks: validate the request to make sure the fields and values are acceptable, and authorize the action to make sure the current user is allowed to perform it. A user might submit a valid post title, for example, yet still lack permission to edit that specific post.

You can validate a request right inside a controller. As your validation rules grow, you can move them into a Form Request class, which lets you keep the rules and the authorization check in one place. Once Laravel validates the request, pass only the validated fields to Eloquent. Never pass the entire request payload straight to a model, because a client can submit extra fields that your form never showed, including columns users should not be able to change.

$this->authorize('update', $post);

$data = $request->validate([
    'title' => 'required|string',
    'body' => 'required|string',
]);

$post->update($data);

In this example, $this->authorize verifies that the user can update the post, and $request->validate limits the input to the two fields you allow. You can read more about request validation and Form Requests in Laravel’s validation documentation. If you want to organize authorization rules around a specific model or resource, Laravel also supports policies.

2. Eager-load the relationships a page displays

When a page lists posts alongside their authors, tell Eloquent to fetch the authors up front. Eloquent calls this eager loading. If you skip it, Eloquent lazy-loads the relationship the first time your code accesses it. Inside a loop, that causes the N+1 query problem: Eloquent runs one query to fetch the posts, and then it runs a separate query for each post’s author.

To avoid those extra queries on a page that lists posts with their authors, load the relationship when you fetch the posts:

$posts = Post::with('author')->get();

Laravel’s documentation shows how fast those queries add up using books and authors. Fetching 25 books and then loading each author one by one can trigger 26 queries, whereas eager loading the authors cuts that down to two. Load only the relationships the page displays, and keep an eye on loops that read relationship properties. The Eloquent relationship documentation covers eager loading and its alternatives in detail.

3. Use migrations for schema changes and transactions for related writes

Whenever you change your database structure, such as adding a column or creating a table, record the change in a migration. Laravel runs migrations in order, which lets you and your team apply the same schema changes to every database instead of making undocumented manual edits. You can see how Laravel defines and runs them in the migration documentation.

When a single action needs to write several related records that must succeed or fail together, wrap those writes in a database transaction. Creating an order, for instance, also means creating its line items; if one write fails, you do not want the database to keep an order with no items. When you pass a closure to Laravel’s DB::transaction method, Laravel commits all the writes if the closure finishes cleanly and rolls them back if an exception occurs. Wrap only the related writes in a transaction rather than putting every query in one by default. See Laravel’s database transaction documentation for details.

Keep the two tools distinct in your head: you use migrations to track changes to the database structure, and you use transactions to keep a group of data writes consistent.

4. Test requests and database outcomes

Write feature tests for the behavior your users or API clients depend on. A feature test sends an HTTP request through your application and then checks both the response and the resulting database state. For a route that creates posts, you can test that valid input saves the expected post and that invalid input saves nothing. If users are only allowed to edit their own posts, write a test confirming that one user cannot edit another user’s post.

Laravel’s testing documentation recommends feature tests for verifying that the parts of your application work together. You can run your test suite with php artisan test and inspect responses using Laravel’s HTTP test tools. Start with the main success path and the failures that matter most, such as invalid input or an unauthorized action. Your tests will start paying off long before you cover every line of code.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *