Best Laravel Eloquent Tips and Tricks

Page 1

www.techtic.com | info@techtic.com


Laravel Tips List of Laravel Tips 1. Increments and Decrements

13. Raw query methods

2. XorY methods

14. Replicate: make a copy of a row

3. Model boot() method

15. Chunk() method for big tables

4. Relationship with conditions and ordering

16. Create additional things when creating a

5. Model properties: timestamps, appends etc.

model

6. Find multiple entries

17. Override updated_at when saving

7. WhereX

18. What is the result of an update()?

8. Order by relationship

19. Transform brackets into an Eloquent query

9. Eloquent::when() – no more if-else’s

20. orWhere with multiple parameters

10. BelongsTo Default Models

21. onDelete('set null')

11. Order by Mutator

22. dropForeign([]);

12. Default ordering in global scope

23. Model Validation

www.techtic.com | info@techtic.com


Laravel Tips 1. Increments and Decrements Instead of this:

Do this:

Also these will work:

www.techtic.com | info@techtic.com


Laravel Tips 2. XorY Methods Eloquent has quite a few functions that combine two methods, like “please do X, otherwise do Y”. Ex 1 – findOrFail(): Instead of:

Do this:

www.techtic.com | info@techtic.com


Laravel Tips 2. XorY Methods Ex 2 – firstOrCreate():

Instead of:

Do this:

www.techtic.com | info@techtic.com


Laravel Tips 3. Model boot() method There is a magical place called boot() in an Eloquent model where you can override default behavior:

Probably one of the most popular examples is setting some field value at the moment of creating the model object.

www.techtic.com | info@techtic.com


Laravel Tips 4. Relationship with conditions and ordering Define Relationship:

Already add where or orderBy? For example, if you want a specific relationship for some type of users, also ordered by email, you can do this:

www.techtic.com | info@techtic.com


Laravel Tips 5. Model properties: timestamps, appends etc. There are a few “parameters” of an Eloquent model, in the form of properties of that class. The most popular ones are probably these:

there’s more:

www.techtic.com | info@techtic.com


Laravel Tips 6. Find multiple entries find() Method

Few people know about that it can accept multiple IDs as an array:

www.techtic.com | info@techtic.com


Laravel Tips 7. WhereX There’s an elegant way to turn this:

Do this:

Also, there are some pre-defined methods in Eloquent, related to date/time:

www.techtic.com | info@techtic.com


Laravel Tips 8. Order by Relationship Separate relationship for the latest post on the topic:

And then, in our controller, we can do this “magic�:

www.techtic.com | info@techtic.com


Laravel Tips 9 Eloquent::when() – no more if-else’s write conditional queries with “if-else”, something like this:

there’s a better way – to use when():

www.techtic.com | info@techtic.com


Laravel Tips 9 Eloquent::when() – no more if-else’s It may not feel shorter or more elegant, but the most powerful is passing of the parameters:

www.techtic.com | info@techtic.com


Laravel Tips 10 BelongsTo Default Models Post belonging to Author and then Blade code:

But what if the author is deleted, or isn’t set for some reason? You will get an error, something like “property of non-object”. Of course, you can prevent it like this:

But you can do it on Eloquent relationship level:

www.techtic.com | info@techtic.com


Laravel Tips 11 Order by Mutator Guess you have this:

Now, you want to order by that full_name? This won’t work:

Solution is simple. We need to order the results after we get them.

Function name is different – it’s not orderBy, it’s sortBy.

www.techtic.com | info@techtic.com


Laravel Tips 12 Default ordering in global scope What if you want to have User::all() always be ordered by name field? You can assign a global scope. Let’s go back to the boot() method, which we mentioned already above.

www.techtic.com | info@techtic.com


13 Raw query methods Add raw queries to our Eloquent statements. functions for that.

www.techtic.com | info@techtic.com


Laravel Tips 14 Replicate: make a copy of a row Short one. Without deep explanations, here’s the best way to make a copy of database entry:

www.techtic.com | info@techtic.com


Laravel Tips 15 Chunk() method for big tables Still powerful – to process bigger datasets, you can chunk them into pieces. Instead of:

Do this:

www.techtic.com | info@techtic.com


Laravel Tips 16 Create additional things when creating a model This Artisan command:

There are three useful flags to generate related files to the model?

 m will create a migration file  c will create a controller  r will indicate that controller should be resourceful

www.techtic.com | info@techtic.com


Laravel Tips 17 Override updated_at when saving ->save() method can accept parameters? As a result, we can tell it to “ignore� updated_at default functionality to be filled with current timestamp. See this:

Overriding default updated_at with our pre-defined one.

www.techtic.com | info@techtic.com


Laravel Tips 18 What is the result of an update()? This code actually returns?

what would that $result contain? The answer is affected rows. So if you need to check how many rows were affected, you don’t need to call anything else – update() method will return this number for you.

www.techtic.com | info@techtic.com


Laravel Tips 19 Transform brackets into an Eloquent query and-or mix SQL query, like this:

How to translate it into Eloquent? This is the wrong way:

The order will be incorrect. The right way is a little more complicated, using closure functions as sub-queries:

www.techtic.com | info@techtic.com


Laravel Tips 20 orWhere with multiple parameters pass an array of parameters to orWhere(). “Usual� way:

Do this:

www.techtic.com | info@techtic.com


Laravel Tips 21 onDelete('set null') Used onDelete('cascade'); on foreign keys in Laravel migrations, know about 'set null'? This allows you to preserve models when their related model is deleted.

www.techtic.com | info@techtic.com


Laravel Tips 22 dropForeign([]); when rolling back multiple foreign keys using array syntax didn't work.

the array syntax on dropForeign is for dropping a foreign key using a shorthand column name.

www.techtic.com | info@techtic.com


Laravel Tips 22 dropForeign([]); Here is drop foreign:

www.techtic.com | info@techtic.com


Laravel Tips 22 dropForeign([]); abstracted call to dropIndexCommand which looks like this:

www.techtic.com | info@techtic.com


Laravel Tips 23 Model Validation This approach was inspired by the Elixir framework, Phoenix.

www.techtic.com | info@techtic.com


Laravel Tips 23 Model Validation

www.techtic.com | info@techtic.com


Laravel Tips 23 Model Validation if your front-end only ends values that have changes for updating, you don't want all fields marked as required.

www.techtic.com | info@techtic.com


Techtic Solutions, Inc. is one of the most trusted Laravel development company with 10+ years of web development experience. Our team of experienced Laravel developers are adept at building simple to the most complex website apps seamlessly using Laravel PHP frameworks. Our clients swear by the codes we write – they are simple, expressive and scalable. We help build sophisticated websites that help maximize ROI for your business. Get in touch if you are looking to hire Certified Laravel developers to deliver, secure, high performance and faster web applications.

Our Services: Custom Laravel Web Development Laravel CMS development Laravel Application Development Laravel Ecommerce Development Laravel Enterprise Solution

Laravel Customization Laravel Theme/Template Design Laravel Plugin Development Laravel REST API Development Laravel Support & Maintenance

www.techtic.com | info@techtic.com


About Techtic Solutions Techtic Solutions is a 9+ years young IT firm offering solutions to various verticals for branding, online marketing, web and mobile applications design & development. With the vast experience of designing & developing 3000+ web projects, 150+ mobile app development projects & 200+ digital marketing projects. Our efficient team of 50+ engineers, marketers, designers & business analysts have track record of offering the most intuitive, efficient & winning solutions to the small, medium and large businesses & corporates to successfully address their business models accuracy & enhancements. Enabling businesses with technological advancements to improve the business model, increase sales channels is the vision of Techtic Solutions. Our professionals work in some of the most innovative areas like Ionic, Swift, iOS, Android, Magento 2.X, Laravel, Yii, AngularJS, CodeIgniter, WordPress and many other open source technologies. Our efficient team management, quality control and willingness to deliver the most innovative solutions to our customers are what set us apart from other I.T. vendors. Continued on Next Page www.techtic.com | info@techtic.com


About Techtic Solutions Techtic is an innovative technology agency with a cavalry of multi-talented and pulsating professionals in quest of challenges to deliver quality digital products. We use leading project development methodology, super efficient process and most advanced tool chain.

Industries we serve

Services Mobile App Development React Native Development Full Stack Development Laravel Development Node.JS Development Angular Development React JS Development WorkPress Development Magento Development IOT Development Digital Marketing

Travel Social Networking Life Style Health & Fitness Productivity Business Navigation Entertainment Advertising Real Estate

www.techtic.com | info@techtic.com


Contact Us Visit us: https://www.techtic.com Email: info@techtic.com Phone: +1 201.793.8324

Source by: https://laravel-news.com/eloquent-tips-tricks


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.