TOPIC COLLECTION
DB Models and Eloquent.
A collection of 100 practical ideas to make everyday Laravel work a little smoother.
100 TIPS01Reuse or Clone Query()Typically, we need to query multiple time from a filtered query. So, most of the time we use query() methodDB Models and Eloquent02Remember to Use Bindings in Your Raw QueriesYou can pass an array of bindings to most raw query methods to avoid SQL injection.DB Models and Eloquent03Small Cheat-sheet for Using Full-text Search with Laravel on MysqlMigration Natural languageDB Models and Eloquent04Merging Eloquent CollectionsThe Eloquent collection's merge method uses the id to avoid duplicated models. But if you are merging collections of different Models, it can cause get you…DB Models and Eloquent05Perform Operation without Modifying Updated_at FieldIf you would like to perform model operations without the model having its updated at timestamp modified, you may operate on the model within a closure…DB Models and Eloquent06You Can Write Transaction-aware CodeUsing DB::afterCommit method you can write code that will only be executed if the transaction gets committed and discarded if the transaction is rolled back.DB Models and Eloquent07Eloquent Scopes Inside of Other RelationshipsDid you know that you can use Eloquent scopes inside of defining other relationships? app/Models/Lesson.phpDB Models and Eloquent08New `Rawvalue()` Method Since Laravel 9.37Laravel 9.37 has a new rawValue() method to get a value from a SQL expression. Here are some examples from the pull requestDB Models and Eloquent09Load Data Faster When the Targeted Value Is an IntegerInstead of using the 𝘄𝗵𝗲𝗿𝗲𝗜𝗻() method to load a large range of data when the targeted value is an integer, use 𝘄𝗵𝗲𝗿𝗲𝗜𝗻𝘁𝗲𝗴𝗲𝗿𝗜𝗻𝗥𝗮𝘄()…DB Models and Eloquent10Load Data Completed Between Two TimestampsUse 𝘄𝗵𝗲𝗿𝗲𝗕𝗲𝘁𝘄𝗲𝗲𝗻 to load records between two timestamps, you can pass the fallback value using the null coalescing operator (??).DB Models and Eloquent11Pass a Raw Query to Order Your ResultsYou can pass a raw query to order your results. For example, sorting tasks by how long before the due date they were completed.DB Models and Eloquent12Eloquent Where Date MethodsIn Eloquent, check the date with functions whereDay() , whereMonth() , whereYear() , whereDate() and whereTime() .DB Models and Eloquent13Increments and DecrementsIf you want to increment some DB column in some table, just use increment() function. Oh, and you can increment not only by 1, but also by some number, like 50.DB Models and Eloquent14No Timestamp ColumnsIf your DB table doesn't contain timestamp fields created at and updated at , you can specify that Eloquent model wouldn't use them, with $timestamps =…DB Models and Eloquent15Soft-deletes: Multiple RestoreWhen using soft-deletes, you can restore multiple rows in one sentence.DB Models and Eloquent16Model All: ColumnsWhen calling Eloquent's Model::all() , you can specify which columns to return.DB Models and Eloquent17To Fail or Not to FailIn addition to findOrFail() , there's also Eloquent method firstOrFail() which will return 404 page if no records for query are found.DB Models and Eloquent18Column Name ChangeIn Eloquent Query Builder, you can specify "as" to return any column with a different name, just like in plain SQL query.DB Models and Eloquent19Map Query ResultsAfter Eloquent query you can modify rows by using map() function in Collections.DB Models and Eloquent20Change Default Timestamp FieldsWhat if you’re working with non-Laravel database and your timestamp columns are named differently? Maybe, you have create time and update time. Luckily, you…DB Models and Eloquent21Quick Order by Created_atInstead of: You can do it quickerDB Models and Eloquent22Automatic Column Value When Creating RecordsIf you want to generate some DB column value when creating record, add it to model's boot() method. For example, if you have a field "position" and want to…DB Models and Eloquent23Db Raw Query Calculations Run FasterUse SQL raw queries like whereRaw() method, to make some DB-specific calculations directly in query, and not in Laravel, usually the result will be faster.…DB Models and Eloquent24More Than One ScopeYou can combine and chain Query Scopes in Eloquent, using more than one scope in a query. ModelDB Models and Eloquent25No Need to Convert CarbonIf you're performing whereDate() and check today's records, you can use Carbon's now() and it will automatically be transformed to date. No need to do -…DB Models and Eloquent26Grouping by First LetterYou can group Eloquent results by any custom condition, here's how to group by first letter of user's nameDB Models and Eloquent27Never Update the ColumnIf you have DB column which you want to be set only once and never updated again, you can set that restriction on Eloquent Model, with a mutatorDB Models and Eloquent28Find ManyEloquent method find() may accept multiple parameters, and then it returns a Collection of all records found, not just one ModelDB Models and Eloquent29Find Many and Return Specific ColumnsEloquent method find() may accept multiple parameters, and then it returns a Collection of all records found with specified columns, not all columns of modelDB Models and Eloquent30Find by KeyYou can also find multiple records with whereKey() method which takes care of which field is exactly your primary key ( id is the default, but you may…DB Models and Eloquent31Use Uuid Instead of Auto-incrementYou don't want to use auto incrementing ID in your model? MigrationDB Models and Eloquent32Sub-selects in Laravel WayFrom Laravel 6, you can use addSelect() in Eloquent statement, and do some calculation to that added column.DB Models and Eloquent33Hide Some ColumnsWhen doing Eloquent query, if you want to hide specific field from being returned, one of the quickest ways is to add - makeHidden() on Collection result.DB Models and Eloquent34Exact Db ErrorIf you want to catch Eloquent Query exceptions, use specific QueryException instead default Exception class, and you will be able to get the exact SQL code…DB Models and Eloquent35Soft-deletes with Query BuilderDon't forget that soft-deletes will exclude entries when you use Eloquent, but won't work if you use Query Builder.DB Models and Eloquent36Good Old SQL QueryIf you need to execute a simple SQL query, without getting any results - like changing something in DB schema, you can just do DB::statement() .DB Models and Eloquent37Use Db TransactionsIf you have two DB operations performed, and second may get an error, then you should rollback the first one, right?DB Models and Eloquent38Update or CreateIf you need to check if the record exists, and then update it, or create a new record otherwise, you can do it in one sentence - use Eloquent method…DB Models and Eloquent39Forget Cache on SaveIf you have cache key like posts that gives collection, and you want to forget that cache key on new store or update, you can call static saved function on…DB Models and Eloquent40Change Format of Created_at and Updated_atTo change the format of created at you can add a method in your model like this: Since Laravel 9DB Models and Eloquent41Storing Array Type into JSONIf you have input field which takes an array and you have to store it as a JSON, you can use $casts property in your model. Here images is a JSON attribute.DB Models and Eloquent42Make a Copy of the ModelIf you have two very similar Models (like shipping address and billing address) and you need to make a copy of one to another, you can use replicate()…DB Models and Eloquent43Reduce MemorySometimes we need to load a huge amount of data into memory. For example: But this can be slow if we have really huge data, because Laravel prepares objects…DB Models and Eloquent44Force Query without $Fillable/$guardedIf you create a Laravel boilerplate as a "starter" for other devs, and you're not in control of what THEY would later fill in Model's $fillable/$guarded,…DB Models and Eloquent453-level Structure of Parent-childrenIf you have a 3-level structure of parent-children, like categories in an e-shop, and you want to show the number of products on the third level, you can…DB Models and Eloquent46Perform Any Action on FailureWhen looking for a record, you may want to perform some actions if it's not found. In addition to - firstOrFail() which just throws 404, you can perform any…DB Models and Eloquent47Check If Record Exists or Show 404Don't use find() and then check if the record exists. Use findOrFail(). Shorter wayDB Models and Eloquent48Abort If Condition Failedabort if() can be used as shorter way to check condition and throw an error page. Shorter wayDB Models and Eloquent49Fill a Column Automatically While You Persist Data to the DatabaseIf you want to fill a column automatically while you persist data to the database (e.g: slug) use Model Observer instead of hard code it every timeDB Models and Eloquent50Extra Information About the QueryYou can call the explain() method on queries to know extra information about the query.DB Models and Eloquent51Using the Doesntexist() Method in LaravelPractical Laravel guidance for using the doesntexist() method in laravel, with examples and copyable PHP code.DB Models and Eloquent52Trait That You Want to Add to a Few Models to Call Their Boot() Method AutomaticallyIf you have a Trait that you want to add to a few Models to call their boot() method automatically, you can call Trait's method as boot[TraitName]DB Models and Eloquent53There Are Two Common Ways of Determining If a Table Is Empty in LaravelThere are two common ways of determining if a table is empty in Laravel. Calling exists() or count() directly on the model!DB Models and Eloquent54How to Prevent “Property of Non-object” ErrorPractical Laravel guidance for how to prevent “property of non-object” error, with examples and copyable PHP code.DB Models and Eloquent55Get Original Attributes After Mutating an Eloquent RecordGet original attributes after mutating an Eloquent record you can get the original attributes by calling getOriginal()DB Models and Eloquent56A Simple Way to Seed a DatabaseA simple way to seed a database in Laravel with a .sql dump fileDB Models and Eloquent57The Crossjoinsub Method of the Query ConstructorUsing the CROSS JOIN subqueryDB Models and Eloquent58Belongs to Many Pivot Table NamingTo determine the table name of the relationship's intermediate table, Eloquent will join the two related model names in alphabetical order.DB Models and Eloquent59Order by Pivot FieldsBelongsToMany::orderByPivot() allows you to directly sort the results of a BelongsToMany relationship query.DB Models and Eloquent60Find a Single Record from a DatabaseThe sole() method will return only one record that matches the criteria. If no such entry is found, then a NoRecordsFoundException will be thrown. If…DB Models and Eloquent61Automatic Records ChunkingSimilar to each() method, but easier to use. Automatically splits the result into parts (chunks).DB Models and Eloquent62Updating the Model without Dispatching EventsSometimes you need to update the model without sending any events. We can now do this with the updateQuietly() method, which under the hood uses the…DB Models and Eloquent63Periodic Cleaning of Models from Obsolete RecordsTo periodically clean models of obsolete records. With this trait, Laravel will do this automatically, only you need to adjust the frequency of the…DB Models and Eloquent64Immutable Dates and Casting to ThemLaravel 8.53 introduces the immutable date and immutable datetime castes that convert dates to Immutable .DB Models and Eloquent65The Findorfail Method Also Accepts a List of IdsThe findOrFail method also accepts a list of ids. If any of these ids are not found, then it "fails".DB Models and Eloquent66Prunable Trait to Automatically Remove Models from Your DatabaseNew in Laravel 8.50: You can use the Prunable trait to automatically remove models from your database. For example, you can permanently remove soft deleted…DB Models and Eloquent67Withaggregate MethodUnder the hood, the withAvg/withCount/withSum and other methods in Eloquent use the 'withAggregate' method. You can use this method to add a subselect based…DB Models and Eloquent68Date ConventionUsing the something at convention instead of just a boolean in Laravel models gives you visibility into when a flag was changed – like when a product went live.DB Models and Eloquent69Eloquent Multiple UpsertsThe upsert() method will insert or update multiple records. - First array: the values to insert or update - Second: unique identifier columns used in the…DB Models and Eloquent70Retrieve the Query Builder After Filtering the ResultsTo retrieve the Query Builder after filtering the results: you can use - toQuery() . The method internally use the first model of the collection and a…DB Models and Eloquent71Custom CastsYou can create custom casts to have Laravel automatically format your Eloquent model data. Here's an example that capitalises a user's name when it is…DB Models and Eloquent72Order Based on a Related Model's Average or CountDid you ever need to order based on a related model's average or count? It's easy with Eloquent!DB Models and Eloquent73Return Transactions ResultIf you have a DB transaction and want to return its result, there are at least two ways, see the exampleDB Models and Eloquent74Remove Several Global Scopes from QueryWhen using Eloquent Global Scopes, you not only can use MULTIPLE scopes, but also remove certain scopes when you don't need them, by providing the array to…DB Models and Eloquent75Order JSON Column AttributeWith Eloquent you can order results by a JSON column attributeDB Models and Eloquent76Get Single Column's Value from the First ResultYou can use value() method to get single column's value from the first result of a queryDB Models and Eloquent77Check If Altered Value Changed KeyEver wanted to know if the changes you've made to a model have altered the value for a key? No problem, simply reach for originalIsEquivalent.DB Models and Eloquent78New Way to Define Accessor and MutatorNew way to define attribute accessors and mutators in Laravel 8.77DB Models and Eloquent79Another Way to Do Accessors and MutatorsIn case you are going to use the same accessors and mutators in many models , You can use custom casts instead.DB Models and Eloquent80When Searching for the First Record, You Can Perform Some ActionsWhen searching for the first record, you want to perform some actions, when you don't find it. firstOrFail() throws a 404 Exception.DB Models and Eloquent81Directly Convert Created_at Date to Human Readable FormatDid you know you can directly convert created at date to human readable format like 1 minute ago, 1 month ago using diffForHumans() function. Laravel…DB Models and Eloquent82Ordering by an Eloquent AccessorOrdering by an Eloquent Accessor! Yes, that's doable. Instead of ordering by the accessor on the DB level, we order by the accessor on the returned Collection.DB Models and Eloquent83Check for Specific Model Was Created or FoundIf you want to check for specific model was created or found, use wasRecentlyCreated model attribute.DB Models and Eloquent84Laravel Scout with Database DriverWith laravel v9 you can use Laravel Scout (Search) with database driver. No more where likes!DB Models and Eloquent85Make Use of the Value Method on the Query BuilderMake use of the value method on the query builder to execute a more efficient query when you only need to retrieve a single column.DB Models and Eloquent86Pass Array to Where MethodLaravel you can pass an array to the where method.DB Models and Eloquent87Return the Primary Keys from Models CollectionDid you know modelsKeys() eloquent collection method? It returns the primary keys from models collection.DB Models and Eloquent88Force Laravel to Use Eager LoadingIf you want to prevent a lazy loading in your app, you only need to add following line to the boot() method in your AppServiceProviderDB Models and Eloquent89Make All Your Models Mass AssignableIt is not a recommended approach for security reasons, but it is possible. When you want do this, you don't need to set an empty $guarded array for every…DB Models and Eloquent90Hiding Columns in Select All StatementsIf you use Laravel v8.78 and MySQL 8.0.23 and onwards, you can define choosen columns as "invisible". Columns which are define as invisible will be hidden…DB Models and Eloquent91JSON Where ClausesLaravel offers helpers to query JSON columns for databases that support them. Currently, MySQL 5.7+, PostgreSQL, SQL Server 2016, and SQLite 3.9.0 (using…DB Models and Eloquent92Get All the Column Names for a TablePractical Laravel guidance for get all the column names for a table, with examples and copyable PHP code.DB Models and Eloquent93Compare the Values of Two ColumnsYou can use whereColumn method to compare the values of two columns.DB Models and Eloquent94Accessor CachingAs of Laravel 9.6, if you have a computationally intensive accessor, you can use the shouldCache method.DB Models and Eloquent95New Scalar() MethodIn Laravel 9.8.0, the scalar() method was added that allows you to retrieve the first column of the first row from the query result.DB Models and Eloquent96Select Specific ColumnsTo select specific columns on a model you can use the select method -- or you can pass an array directly to the get method!DB Models and Eloquent97Chain Conditional Clauses to the Query without Writing If-else StatementsThe "when" helper in the query builder is🔥 You can chain conditional clauses to the query without writing if-else statements.DB Models and Eloquent98Override Connection Attribute in ModelsOverriding the database connection attribute for individual models in Laravel can be a powerful technique. Here are a few use cases where you might find it…DB Models and Eloquent99Using Column Names in Where Clauses (Dynamic Where Clauses)You can use column names in where clause to make dynamic where clauses. In the following example, we use instead of .DB Models and Eloquent100Using Firstorcreate()You can use firstOrCreate() to find the first record matching the attributes or create it if it doesn't exist.DB Models and Eloquent