🔥 Laravel/web development tips. Some of them are not very well known.

1 RT = 1 tip

First 3 are free.

THREAD
1. People underutilize the exception handler.

You can tell the app what response to return when a specific exception is encountered.

This is the simplest example. There's many more use cases.
2. You can return Mailables as responses from controllers. It will show the rendered version in the browser.

Great for debugging/tweaking the design.
3.1. There's great value in understanding how object state of Models works. This is mostly relevant in (Feature) tests because they touch many parts of your codebase in one PHP/Laravel App state.

For example, use $model->is($anotherModel) to check if they refer to the same row.
3.2. When a relationship is already loaded and "cached" on the model instance, you'll have to refresh it.

`$domain->refresh();` to refresh its attributes

`$tenant->load('primary_domain');` to update the `primary_domain` relationship on the $tenant instance
4. Laravel Nova lets you show different resources/tools/cards/... based on an if check.

Extremely handy when you have multiple admin panels in a single app.
5. Closure validation rules are 🔥. They're often better than creating a class just for a single use.

Create a class if it's used on multiple places or way too complex.
6. Relevant for people building packages 📦

It's IMO better to use static properties and have "self-contained" behavior & configuration. Than to have a billion config keys. Especially when building large packages.

Makes the package more extensible, by consisting of atomic parts
Here's another example of the Model state stuff mentioned above.

Except...

It's multi-tenant!

Tip 7: It's incredibly easy to use http://tenancyforlaravel.com  with Tinker 😎
8. Vue tip. Double indentation of data() sucks.

Use arrow functions instead. https://twitter.com/samuelstancl/status/1285486044561969154
9. Laravel Telescope is great for so many things.

One of them is examining sent emails ✉️

You usually don't need a service like Mailtrap. Just use the `log` mail driver and install Telescope.

(image stolen from the internet)
10. If you want to identify teams, workspaces, etc by path, you don't have to pass the team ID to every route.

In the example below, the value reaches the middleware, where you can do some stuff, and then is REMOVED from the route parameters before being passed to the action.
11. You can use where{X}and{Y}() in Eloquent.

Not recommended in most cases, but interesting.

(image stolen from the internet)
12. When using Nova, I often found myself creating accessors and mutators as the layer between Nova and my models.

Sometimes, you need to transform the user input before storing it.

E.g. prices stored in cents, without tax.

Here's a better solution: https://twitter.com/vguerrerobosch/status/1306592445895864321
13. If you're debugging your app and you'd like to examine more things - e.g. the stack trace, executed queries, app context, ...

You can use ddd() instead of dd().

I tend to forget about this one, but it's super useful.
14. Comparing changes on 'saving' using:

$model->getOriginal()

in Eloquent event listeners can be very useful.

One such use case is checking whether an order is locked. If it is, the only write action we permit is unlocking it. Only then can changes be made.
15.1. Eloquent listeners are awesome.

Example: Default value set on creation.
15.2. Example: Deleting associated files on deletion.
15.3. Example: Checking a parent relationship for some things.

Such as, checking if an Order is locked inside an OrderProduct.

OrderProducts cannot be added to/changed in a locked order.
16. Valet for PHP and MySQL/Redis using:
- docker-compose per project
- or DBngin globally

is the absolute best development setup for macOS and Linux.

Fight me.
17. Laravel migrations have a very nice syntax for foreign keys.

I didn't know about this for so long.

Instead of:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');

You do:
$table->foreignId('user_id')->constrained();
18. You can return "false" from a -ing() Eloquent event listener (creating, updating, saving, deleting) to cancel the action.

This is similar to how I was throwing an exception based on certain things in the example with order locking.
20.1. This won't fit into one tweet but there's so much cool stuff you can do with Eloquent.

You DON'T have to go raw SQL when you hit a performance issue with Eloquent. There's so many "secret" techniques.

Example: You can create scopes to add specific selects to your queries.
20.2 You can create dynamic relationships — this relationship is based on a column that's added using a subquery, in a scope.

And so much more.
21. You can add a tags() method to a job. Anything you return from this method will be displayed in Horizon.

Very useful if you want to tag jobs with things like the user/tenant id.
22. Not too useful but interesting: When I was looking online for some more tips, I found a website by @TightenCo

https://laravel-tricks.com/ 

Users can submit tips and vote on them

Seems like it's been popular ~5 years ago. Shame that it's not used anymore, the idea is very nice!
23.1. There's an interesting difference between global middleware and route-level middleware.

Global middleware is executed BEFORE the route data is parsed. Then the controller constructor is executed. And then the route middleware is executed.
23.2. Most apps won't need to use this, but this creates an important difference between those two middleware types

Global middleware can be used to affect the application state very early on (e.g. change DB connection based on domain). Before dependencies are injected in ctrlrs
24. This one is less obscure.

The $loop variable.

It greatly complements Tailwind-styled tables.

Striped tables done easily 🎉
25. You can explicitly bind objects to routes. You don't have to use route model binding only. Custom objects work perfectly well too.

This example is from Tenancy v2 when we had an ActiveRecord-style custom Tenant object.
26. If you're using Livewire v2... did you know that you can have component methods that listen to *model properties property updates*?

Sounds a bit confusing, so here's an example: https://twitter.com/LiamHammett/status/1307716271904096262
aaand it's bed time, thanks everyone for RTs

I'll try to continue with as many as possible tomorrow 🔥

hope I dream of some laravel tips at night because this is starting to get hard 😅

goodnight! 💤
27. Throw ValidationExceptions manually, even if you're not using the Validator.

You'll get the handling (error bag/JSON response) for free. https://twitter.com/AndreSayej/status/1274399057016958977
28. Custom collections are extremely underutilized and let you do super cool things like this: https://twitter.com/timacdonald87/status/1253524892055560193
You can follow @samuelstancl.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: