๐ฅ Epic Laravel Tips Thread ๐ฅ [ Part 1 ] I decided to create weekly threads and share epic @laravelphp tips that will lead to a cleaner and more performant code!
๐ฅ Epic Laravel ๐ฅ - Tip No. 1 [ Eloquent Global Query Scopes ] Implementing your own eloquent global query scopes can be a quick and straightforward approach to ensure that all queries for a given model are subject to certain limitations:
2/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 2 [ Conditional Relationships ]
Relationships allow for powerful method chaining and querying. However, for consistency reasons consider creating a separate relationship method that includes the desired chaining or querying:
3/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 3 [ optional() helper method ] The optional function takes any input and allows you to access the object's attributes and methods. If an object is null, properties and methods will return null rather than throwing an error:
4/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 4 [ Order by Relationship ]
Eloquent ORM appears to be a straightforward mapper, yet it has some semi-hidden features and lesser-known uses. Did you know that you can order by relationship? Here's how:
5/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 5 [ Laravel API withoutWrapping(); ]
When utilizing API Resources, the response is automatically wrapped in a 'data' object. Here's how to get rid of it:
6/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 6 [ Disable Lazy Loading ]
Laravel 8.43.0 introduces a new helper method that allows you to disable lazy loading entirely. To do so, in your AppServiceProvider.php, inside the boot() method you refer to this new helper method like this:
7/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 7 [ Pagination Query String ]
If you want to paginate two tables on the same page, you can assign a different query string parameter for each of them:
8/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 8 [ Partial Resource Routes ]
Instead of the entire list of default actions, you can define a subset of actions the controller should handle when defining a resource route:
9/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 9 [ Retrieving a subset of the input data ]
The only and except methods can be used to retrieve a subset of the input data:
10/11
๐ฅ Epic Laravel ๐ฅ - Tip No. 10 [ Testing: spying facades ]
If you want to spy on a facade, use the spy method on that facade. Spies record every interaction between the spy and the code under test, allowing you to make assertions after the code has been run:
โข โข โข
Missing some Tweet in this thread? You can try to
force a refresh