TOPIC COLLECTION

Models Relations.

A collection of 36 practical ideas to make everyday Laravel work a little smoother.

36 TIPS
36 tips
01Orderby on Eloquent RelationshipsYou can specify orderBy() directly on your Eloquent relationships.Models Relations02Add Where Statement to Many-to-many RelationIn your many-to-many relationships, you can add where statements to your pivot table using the wherePivot method.Models Relations03Get the Newest (or Oldest) Item of Another RelationSince Laravel 8.42, in an Eloquent model, you can define a relation that will get the newest (or oldest) item of another relation.Models Relations04Conditional RelationshipsIf you notice that you use same relationship often with additional "where" condition, you can create a separate relationship method.Models Relations05Raw Db Queries: Havingraw()You can use RAW DB queries in various places, including havingRaw() function after groupBy() .Models Relations06Eloquent Has() DeeperYou can use Eloquent has() function to query relationships even two layers deep!Models Relations07Has Many. How Many Exactly?In Eloquent hasMany() relationships, you can filter out records that have X amount of children records.Models Relations08Default ModelYou can assign a default model in belongsTo relationship, to avoid fatal errors when calling it like {{ $post- user- name }} if $post- user doesn't exist.Models Relations09Use Hasmany to Create ManyIf you have hasMany() relationship, you can use saveMany() to save multiple "child" entries from your "parent" object, all in one sentence.Models Relations10Multi Level Eager LoadingIn Laravel you can Eager Load multiple levels in one statement, in this example we not only load the author relation but also the country relation on the…Models Relations11Eager Loading with Exact ColumnsYou can do Laravel Eager Loading and specify the exact columns you want to get from the relationship.Models Relations12Touch Parent Updated_at EasilyIf you are updating a record and want to update the updated at column of parent relationship (like, you add new post comment and want posts.updated at to…Models Relations13Always Check If Relationship ExistsNever ever do $model- relationship- field without checking if relationship object still exists.Models Relations14Use Withcount() to Calculate Child Relationships RecordsIf you have hasMany() relationship, and you want to calculate “children” entries, don’t write a special query. For example, if you have posts and comments…Models Relations15Extra Filter Query on RelationshipsIf you want to load relationship data, you can specify some limitations or ordering in a closure function. For example, if you want to get Countries with…Models Relations16Load Relationships Always, But DynamicallyYou can not only specify what relationships to ALWAYS load with the model, but you can do it dynamically, in the constructor methodModels Relations17Instead of Belongsto, Use HasmanyFor belongsTo relationship, instead of passing parent's ID when creating child record, use hasMany relationship to make a shorter sentence.Models Relations18Rename Pivot TableIf you want to rename "pivot" word and call your relationship something else, you just use - as('name') in your relationship.Models Relations19Update Parent in One LineIf you have a belongsTo() relationship, you can update the Eloquent relationship data in the same sentenceModels Relations20Laravel 7+ Foreign KeysFrom Laravel 7, in migrations you don't need to write two lines for relationship field - one for the field and one for foreign key. Use method foreignId() .Models Relations21Combine Two "Wherehas"In Eloquent, you can combine whereHas() and orDoesntHave() in one sentence.Models Relations22Check If Relationship Method ExistsIf your Eloquent relationship names are dynamic and you need to check if relationship with such name exists on the object, use PHP function method…Models Relations23Pivot Table with Extra RelationsIn many-to-many relationship, your pivot table may contain extra fields, and even extra relationships to other Model.Models Relations24Load Count On-the-flyIn addition to Eloquent's withCount() method to count related records, you can also load the count on-the-fly, with loadCount()Models Relations25Randomize Relationship OrderYou can use inRandomOrder() to randomize Eloquent query result, but also you can use it to randomize the relationship entries you're loading with query.Models Relations26Filter Hasmany RelationshipsJust a code example from my project, showing the possibility of filtering hasMany relationships.Models Relations27Filter by Many-to-many Relationship Pivot ColumnIf you have a many-to-many relationship, and you add an extra column to the pivot table, here's how you can order by it when querying the list.Models Relations28A Shorter Way to Write WherehasReleased in Laravel 8.57: a shorter way to write whereHas() with a simple condition inside.Models Relations29You Can Add Conditions to Your RelationshipsPractical Laravel guidance for you can add conditions to your relationships, with examples and copyable PHP code.Models Relations30New `Wherebelongsto()` Eloquent Query Builder MethodLaravel 8.63.0 ships with a new whereBelongsTo() Eloquent query builder method. Smiling face with heart-shaped eyesModels Relations31The `Is()` Method of One-to-one Relationships for Comparing ModelsWe can now make comparisons between related models without further database access.Models Relations32`Wherehas()` Multiple ConnectionsPractical Laravel guidance for `wherehas()` multiple connections, with examples and copyable PHP code.Models Relations33Update an Existing Pivot RecordIf you want to update an existing pivot record on the table, use updateExistingPivot instead of syncWithPivotValues .Models Relations34Relation That Will Get the Newest (or Oldest) ItemNew in Laravel 8.42: In an Eloquent model can define a relation that will get the newest (or oldest) item of another relation.Models Relations35Replace Your Custom Queries with OfmanyPractical Laravel guidance for replace your custom queries with ofmany, with examples and copyable PHP code.Models Relations36Avoid Data Leakage When Using Orwhere on a RelationshipReturns: ALL posts where votes are greater than or equal to 100 are returned Returns: Users posts where votes are greater than or equal to 100 are returnedModels Relations