Marian Pop โšก Laravel Magazine Profile picture
๐Ÿง™๐Ÿปโ€โ™‚๏ธ Full-stack (Laravel, Vue, React) ๐Ÿฅท๐Ÿป Creator of https://t.co/28Hx4ltzAl ๐Ÿ›ฐ๏ธ Sharing Laravel insights & ๐ŸŽ™ Podcast at @LaravelMagazine ๐Ÿ‘ค Pronouns: vi/vim

Jan 6, 2022, 11 tweets

๐Ÿ”ฅ 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!

Let's go ๐Ÿงต #epiclaravel ๐Ÿ‘‡๐Ÿป

1/11

๐Ÿ”ฅ 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:

Share this Scrolly Tale with your friends.

A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.

Keep scrolling