THE COMPLETE COLLECTION

All Laravel Tips.

Search practical Laravel guidance, patterns, and code examples across every topic.

369 TIPS
369 tips
01Reuse 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 Eloquent101Orderby on Eloquent RelationshipsYou can specify orderBy() directly on your Eloquent relationships.Models Relations102Add 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 Relations103Get 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 Relations104Conditional RelationshipsIf you notice that you use same relationship often with additional "where" condition, you can create a separate relationship method.Models Relations105Raw Db Queries: Havingraw()You can use RAW DB queries in various places, including havingRaw() function after groupBy() .Models Relations106Eloquent Has() DeeperYou can use Eloquent has() function to query relationships even two layers deep!Models Relations107Has Many. How Many Exactly?In Eloquent hasMany() relationships, you can filter out records that have X amount of children records.Models Relations108Default 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 Relations109Use 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 Relations110Multi 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 Relations111Eager Loading with Exact ColumnsYou can do Laravel Eager Loading and specify the exact columns you want to get from the relationship.Models Relations112Touch 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 Relations113Always Check If Relationship ExistsNever ever do $model- relationship- field without checking if relationship object still exists.Models Relations114Use 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 Relations115Extra 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 Relations116Load 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 Relations117Instead 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 Relations118Rename Pivot TableIf you want to rename "pivot" word and call your relationship something else, you just use - as('name') in your relationship.Models Relations119Update Parent in One LineIf you have a belongsTo() relationship, you can update the Eloquent relationship data in the same sentenceModels Relations120Laravel 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 Relations121Combine Two "Wherehas"In Eloquent, you can combine whereHas() and orDoesntHave() in one sentence.Models Relations122Check 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 Relations123Pivot Table with Extra RelationsIn many-to-many relationship, your pivot table may contain extra fields, and even extra relationships to other Model.Models Relations124Load 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 Relations125Randomize 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 Relations126Filter Hasmany RelationshipsJust a code example from my project, showing the possibility of filtering hasMany relationships.Models Relations127Filter 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 Relations128A Shorter Way to Write WherehasReleased in Laravel 8.57: a shorter way to write whereHas() with a simple condition inside.Models Relations129You Can Add Conditions to Your RelationshipsPractical Laravel guidance for you can add conditions to your relationships, with examples and copyable PHP code.Models Relations130New `Wherebelongsto()` Eloquent Query Builder MethodLaravel 8.63.0 ships with a new whereBelongsTo() Eloquent query builder method. Smiling face with heart-shaped eyesModels Relations131The `Is()` Method of One-to-one Relationships for Comparing ModelsWe can now make comparisons between related models without further database access.Models Relations132`Wherehas()` Multiple ConnectionsPractical Laravel guidance for `wherehas()` multiple connections, with examples and copyable PHP code.Models Relations133Update an Existing Pivot RecordIf you want to update an existing pivot record on the table, use updateExistingPivot instead of syncWithPivotValues .Models Relations134Relation 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 Relations135Replace Your Custom Queries with OfmanyPractical Laravel guidance for replace your custom queries with ofmany, with examples and copyable PHP code.Models Relations136Avoid 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 Relations137Order of MigrationsIf you want to change the order of DB migrations, just rename the file's timestamp, like from 2018 08 04 070443 create posts table.php to 2018 07 04 070443…Migrations138Migration Fields with TimezonesDid you know that in migrations there's not only timestamps() but also timestampsTz() , for the timezone?Migrations139Database Migrations Column TypesThere are interesting column types for migrations, here are a few examples. See all column types on the official documentation.Migrations140Default TimestampWhile creating migrations, you can use timestamp() column type with option useCurrent() and useCurrentOnUpdate() , it will set CURRENT TIMESTAMP as default…Migrations141Migration StatusIf you want to check what migrations are executed or not yet, no need to look at the database "migrations" table, you can launch php artisan migrate:status…Migrations142Add Composite Indexes for Common Query FiltersIndex columns that appear together in frequent filters, joins, or sort orders after checking the actual query plan. A composite index can help a query that…Migrations143Create Migration with SpacesWhen typing make:migration command, you don't necessarily have to use underscore symbol between parts, like create transactions table . You can put the name…Migrations144Create Column After Another ColumnNotice: Only MySQL If you're adding a new column to the existing table, it doesn't necessarily have to become the last in the list. You can specify after…Migrations145Make Migration for Existing TableIf you make a migration for existing table, and you want Laravel to generate the Schema::table() for you, then add "\ in xxxxx table" or "\ to xxxxx table"…Migrations146Output SQL Before Running MigrationsWhen typing migrate --pretend command, you get the SQL query that will be executed in the terminal. It's an interesting way to debug SQL if necessary.Migrations147Anonymous MigrationsThe Laravel team released Laravel 8.37 with anonymous migration support, which solves a GitHub issue with migration class name collisions. The core of the…Migrations148You Can Add "Comment" About a Column Inside Your MigrationsYou can add "comment" about a column inside your migrations and provide useful information.Migrations149Checking for Table / Column ExistenceYou may check for the existence of a table or column using the hasTable and hasColumn methodsMigrations150Group Columns Within an After MethodIn your migrations, you can add multiple columns after another column using the after methodMigrations151Add the Column in the Database Table Only If It's Not Present & Can Drop It If, Its PresentNow you can add the column in the database table only if its not present & can drop it if, its present. For that following methods are introducedMigrations152Method to Set the Default Value for Current TimestampYou can use useCurrent() method for your custom timestamp column to store the current timestamp as a default value.Migrations153$Loop Variable in ForeachInside of foreach loop, check if current entry is first/last by just using $loop variable.Views154You Can Use Blade to Generate More Than HtmlYou can use it to generate any dynamic string or file you want. For example, a shell script or a sitemap file.Views155Short Attribute Syntax for Blade ComponentsAvailable from Laravel 9.32. Current syntaxViews156Share One Variable with Multiple ViewsHave you ever needed to share one variable with multiple views in Laravel? Here's a simple solution for that.Views157Does View File Exist?You can check if View file exists before actually loading it. You can even load an array of views and only the first existing will be actually loaded.Views158Error Code Blade PagesIf you want to create a specific error page for some HTTP code, like 503 - just create a blade file with this code as filename, in…Views159View without ControllersIf you want route to just show a certain view, don't create a Controller method, just use Route::view() function.Views160Blade @AuthInstead of if-statement to check logged in user, use @auth directive. Typical wayViews161Two-level $Loop Variable in BladeIn Blade's foreach you can use $loop variable even in two-level loop to reach parent variable.Views162Create Your Own Blade DirectiveIt’s very easy - just add your own method in app/Providers/AppServiceProvider.php . For example, if you want to have this for replace <br tags with new linesViews163Blade Directives: Includeif, Includewhen, IncludefirstIf you are not sure whether your Blade partial file actually would exist, you may use these condition commandsViews164Use Laravel Blade X Variable Binding to Save Even More SpacePractical Laravel guidance for use laravel blade x variable binding to save even more space, with examples and copyable PHP code.Views165Blade Components PropsPractical Laravel guidance for blade components props, with examples and copyable PHP code.Views166Blade Autocomplete TypehintPractical Laravel guidance for blade autocomplete typehint, with examples and copyable PHP code.Views167Component Syntax TipDid you know that if you pass colon (:) before the component parameter, you can directly pass variables without print statement {{ }} ?Views168Automatically Highlight Nav LinksAutomatically highlight nav links when exact URL matches, or pass a path or route name pattern.Views169Cleanup LoopsDid you know the Blade @each directive can help cleanup loops in your templates?Views170Simple Way to Tidy Up Your Blade ViewsA simple way to tidy up your Blade views! Use the forelse loop , instead of a foreach loop nested in an if statementViews171Checked Blade DirectiveIn Laravel 9, you'll be able to use the cool new "checked" Blade directive. This is going to be a nice addition that we can use to clean up our Blade views…Views172Selected Blade DirectiveIn Laravel 9, you'll be able to use the cool new "selected" Blade directive for HTML select elements.Views173Route Group Within a GroupIn Routes, you can create a group within a group, assigning a certain middleware only to some URLs in the "parent" group.Routing174Declare a Resolveroutebinding Method in Your ModelRoute model binding in Laravel is great, but there are cases where we can't just allow users to easily access resources by ID. We might need to verify their…Routing175Assign Withtrashed() to Route::resource() MethodBefore Laravel 9.35 - only for Route::get() Since Laravel 9.35 - also for Route::resource() !Routing176Skip Input NormalizationLaravel automatically trims all incoming string fields on the request. It's called Input Normalization.Routing177Wildcard SubdomainsYou can create route group by dynamic subdomain name, and pass its value to every route.Routing178What's Behind the Routes?If you use Laravel UI package, you likely want to know what routes are actually behind Auth::routes() ?Routing179Route Model Binding: You Can Define a KeyYou can do Route model binding like Route::get('api/users/{user}', function (User $user) { … } - but not only by ID field. If you want {user} to be a…Routing180Route Fallback: When No Other Route Is MatchedIf you want to specify additional logic for not-found routes, instead of just throwing default 404 page, you may create a special Route for that, at the…Routing181Route Parameters Validation with RegexpWe can validate parameters directly in the route, with “where” parameter. A pretty typical case is to prefix your routes by language locale, like fr/blog…Routing182Rate Limiting: Global and for Guests/usersYou can limit some URL to be called a maximum of 60 times per minute, with throttle:60,1Routing183Query String Parameters to RoutesIf you pass additional parameters to the route, in the array, those key / value pairs will automatically be added to the generated URL's query string.Routing184Separate Routes by FilesIf you have a set of routes related to a certain "section", you may separate them in a special routes/XXXXX.php file, and just include it in routes/web.phpRouting185Translate Resource VerbsIf you use resource controllers, but want to change URL verbs to non-English for SEO purposes, so instead of /create you want Spanish /crear , you can…Routing186Custom Resource Route NamesWhen using Resource Controllers, in routes/web.php you can specify - names() parameter, so the URL prefix in the browser and the route name prefix you use…Routing187Eager Load RelationshipIf you use Route Model Binding and think you can't use Eager Loading for relationships, think again.Routing188Localizing Resource UrisIf you use resource controllers, but want to change URL verbs to non-English, so instead of /create you want Spanish /crear , you can configure it with…Routing189Resource Controllers NamingIn Resource Controllers, in routes/web.php you can specify - names() parameter, so the URL prefix and the route name prefix may be different.Routing190Easily Highlight Your Navbar MenusUse Route::is('route-name') to easily highlight your navbar menusRouting191Generate Absolute Path Using Route() HelperPractical Laravel guidance for generate absolute path using route() helper, with examples and copyable PHP code.Routing192Override the Route Binding Resolver for Each of Your ModelsYou can override the route binding resolver for each of your models. In this example, I have no control over the @ sign in the URL, so using the…Routing193If You Need Public URL, But You Want Them to Be SecuredIf you need public URL but you want them to be secured, use Laravel signed URLRouting194Using Gate in Middleware MethodYou can use the gates you specified in App\Providers\AuthServiceProvider in middleware method.Routing195Simple Route with Arrow FunctionYou can use php arrow function in routing, without having to use anonymous function. To do this, you can use fn() = , it looks easier.Routing196Route ViewYou can use Route::view($uri , $bladePage) to return a view directly, without having to use controller function.Routing197Route Directory Instead of Route FileYou can create a /routes/web/ directory and only fill /routes/web.php with: Now every file inside /routes/web/ act as a web router file and you can organize…Routing198Route Resources GroupingIf your routes have a lot of resource controllers, you can group them and call one Route::resources() instead of many single Route::resource() statements.Routing199Custom Route BindingsDid you know you can define custom route bindings in Laravel? In this example, I need to resolve a portfolio by slug. But the slug is not unique, because…Routing200Two Ways to Check the Route NameHere are two ways to check the route name in Laravel.Routing201Route Model Binding Soft-deleted ModelsBy default, when using route model binding will not retrieve models that have been soft-deleted. You can change that behavior by using withTrashed in your…Routing202Retrieve the URL without Query ParametersIf for some reason, your URL is having query parameters, you can retrieve the URL without query parameters using the fullUrlWithoutQuery method of request…Routing203Customizing Missing Model Behavior in Route Model BindingsBy default, Laravel throws a 404 error when it can't bind the model, but you can change that behavior by passing a closure to the missing method.Routing204Exclude Middleware from a RouteYou can exclude middleware at the route level in Laravel using the withoutMiddleware method.Routing205Controller GroupsInstead of using the controller in each route, consider using a route controller group. Added to Laravel since v8.80Routing206Image ValidationWhile validating uploaded images, you can specify the dimensions you require.Validation207Add Values to the Form Request After ValidationPractical Laravel guidance for add values to the form request after validation, with examples and copyable PHP code.Validation208Access Model Binding in FormrequestsWhen using FormRequests, you can always access the binding model by simply using the following expression $𝘁𝗵𝗶𝘀-…Validation209Rule Which Ensures the Field Under Validation Is Required If Another Field Is AcceptedYou can use required if accepted validation rule which ensures the field under validation is required if another field is accepted (a value of yes, on, 1,…Validation210Custom Validation Error MessagesYou can customize validation error messages per field , rule and language - just create a specific language file resources/lang/xx/validation.php with…Validation211Validate Dates with "Now" or "Yesterday" WordsYou can validate dates by rules before/after and passing various strings as a parameter, like: tomorrow , now , yesterday . Example: 'start date' =…Validation212Validation Rule with Some ConditionsIf your validation rules depend on some condition, you can modify the rules by adding withValidator() to your FormRequest class, and specify your custom…Validation213Change Default Validation MessagesIf you want to change default validation error message for specific field and specific validation rule, just add a messages() method into your FormRequest…Validation214Prepare for ValidationIf you want to modify some field before default Laravel validation, or, in other words, "prepare" that field, guess what - there's a method…Validation215Stop on First Validation ErrorBy default, Laravel validation errors will be returned in a list, checking all validation rules. But if you want the process to stop after the first error,…Validation216Throw 422 Status Code without Using Validate() or Form RequestIf you don't use validate() or Form Request, but still need to throw errors with the same 422 status code and error structure, you can do it manually throw…Validation217Rules Depending on Some Other ConditionsIf your rules are dynamic and depend on some other condition, you can create that array of rules on the flyValidation218With Rule::when() We Can Conditionally Apply Validation RulesThanks to Rule::when() we can conditionally apply validation rules in laravel. In this example we validate the value of the vote only if the user can…Validation219Use This Property in the Request Classes to Stop the Validation of the Whole Request AttributesUse this property in the request classes to stop the validation of the whole request attributes.Validation220Rule::unique Doesn't Take into the Softdeletes Global Scope Applied on the ModelStrange that Rule::unique doesn't take into the SoftDeletes Global Scope applied on the Model, by default.Validation221Validator::sometimes() Method Allows Us to Define When a Validation Rule Should Be AppliedThe laravel Validator::sometimes() method allows us to define when a validation rule should be applied, based on the input provided.Validation222Array Elements ValidationIf you want to validate elements of an array that you submited use dot notation in rules with '\ 'Validation223Password::defaults MethodYou can enforce specific rules when validating user-supplied passwords by using the Password::defaults method. It includes options for requiring letters,…Validation224Form Requests for Validation Redirectionwhen using Form Requests for validation, by default the validation error will redirect back to the previous page, but you can override it. Just define the…Validation225Mac Validation RuleNew mac address validation rule added in Laravel 8.77Validation226Validate Email with Tld Domain RequiredBy default, the email validation rule will accept an email without tld domain (ie: user@laravel )Validation227New Array Validation Rule Required_array_keysLaravel 8.82 adds a required array keys validation rule. The rule checks that all of the specified keys exist in an array.Validation228Position Placeholder in Validation MessagesIn Laravel 9 you can use the :position placeholder in validation messages if you're working with arrays.Validation229Exclude Validation ValueWhen you need to validate a field, but don't actually require it for anything e.g. 'accept terms and conditions', make use of the exclude rule. That way,…Validation230Use Groupby on Collections with Custom Callback FunctionIf you want to group result by some condition which isn’t a direct column in your database, you can do that by providing a closure function.Collections231Laravel Scopes Can Be Combined Using "Higher Order" Orwhere MethodFollowing example from the Docs. BeforeCollections232Multiple Collection Methods in a RowIf you query all results with - all() or - get() , you may then perform various Collection operations on the same result, it won’t query database every time.Collections233Calculate Sum with PaginationHow to calculate the sum of all records when you have only the PAGINATED collection? Do the calculation BEFORE the pagination, but from the same query.Collections234Serial No in Foreach Loop with PaginationWe can use foreach collection items index as serial no (SL) in pagination. it will solve the issue of next pages(?page=2&...) index count from continue.Collections235Higher Order Collection MessageCollections also provide support for "higher order messages", which are short-cuts for performing common actions on collections. This example calculates the…Collections236Get an Existing Key or Insert a Value If It Doesn't Exist and Return the ValueIn Laravel 8.81 getOrPut method to Collections that simplifies the use-case where you want to either get an existing key or insert a value if it doesn't…Collections237Static Times MethodThe static times method creates a new collection by invoking the given closure a specified number of times.Collections238Use Policies for Model-based AuthorizationWhen permissions depend on a specific model, keep the rules in a policy instead of repeating ownership checks across controllers. Laravel can discover a…Auth239Enable Two-factor Authentication with FortifyLaravel Fortify provides a TOTP-based two-factor sign-in flow, including challenge and recovery-code support. Install Fortify and run its published…Auth240Check Multiple Permissions at OnceIn addition to @can Blade directive, did you know you can check multiple permissions at once with @canany directive?Auth241Authenticate Users with More OptionsIf you only want to authenticate users that are also "activated", for example, it's as simple as passing an extra argument to Auth::attempt() .Auth242More Events on User RegistrationWant to perform some actions after new user registration? Head to app/Providers/EventServiceProvider.php and add more Listeners classes, and then in those…Auth243Did You Know About Auth::once()?You can login with user only for ONE REQUEST, using method Auth::once() . No sessions or cookies will be utilized, which means this method may be helpful…Auth244Change API Token on Users Password UpdateIt's convenient to change the user's API Token when its password changes. ModelAuth245Override Permissions for Super AdminIf you've defined your Gates but want to override all permissions for SUPER ADMIN user, to give that superadmin ALL permissions, you can intercept gates…Auth246Custom Authentication EventsLaravel's authentication system fires various events during the authentication process, allowing you to hook into these events and perform additional…Auth247Testing Email into Laravel.logIf you want to test email contents in your app but unable or unwilling to set up something like Mailgun, use .env parameter MAIL DRIVER=log and all the…Mail248You Don’t Have to Store Files to Use Them as Email Attachments in LaravelSimply use attachData to add user uploaded files in Mailables. Here's a snippet from a Mailable class using it.Mail249Preview MailablesIf you use Mailables to send email, you can preview the result without sending, directly in your browser. Just return a Mailable as route resultMail250Preview Mail without MailablesYou can also preview your email without Mailables. For instance, when you are creating notification, you can specify the markdown that may be use for your…Mail251Default Email Subject in Laravel NotificationsIf you send Laravel Notification and don't specify subject in toMail() , default subject is your notification class name, CamelCased into Spaces.Mail252Send Notifications to AnyoneYou can send Laravel Notifications not only to a certain user with $user- notify() , but also to anyone you want, via Notification::route() , with so-called…Mail253Set Conditional Object PropertiesYou can use the when() or unless() methods in your MailMessage notifications to set conditional object properties like a call to action.Mail254Cache Laravel's Bootstrap Files During DeploymentFor production releases, run Laravel's optimize command to cache configuration, events, routes, and views togetherArtisan255Create Artisan Commands for Repeatable MaintenanceTurn recurring operational work into a command so it can be run manually, scheduled, logged, and reviewed like the rest of the applicationArtisan256Artisan Command ParametersWhen creating Artisan command, you can ask the input in variety of ways: $this- confirm() , $this- anticipate() , $this- choice() .Artisan257Execute a Closure After Command Runs without Errors or Has Any ErrorsWith Laravel scheduler you can execute a Closure when a command runs without errors with the onSuccess() method and also when a command has any errors with…Artisan258Run Artisan Commands on Specific EnvironmentsTake control of your Laravel scheduled commands. Run them on specific environments for ultimate flexibility.Artisan259Maintenance ModeIf you want to enable maintenance mode on your page, execute the down Artisan command: Then people would see default 503 status page.Artisan260Artisan Command HelpTo check the options of artisan command, Run artisan commands with --help flag. For example, php artisan make:model --help and see how many options you haveArtisan261Exact Laravel VersionFind out exactly what Laravel version you have in your app, by running command php artisan --versionArtisan262Launch Artisan Command from AnywhereIf you have an Artisan command, you can launch it not only from Terminal, but also from anywhere in your code, with parameters. Use Artisan::call() methodArtisan263Hide Your Custom CommandIf you don't want to show a specific command on the artisan command list, set hidden property to trueArtisan264Skip MethodLaravel the skip method in scheduler You can use skip in your commands to skip an executionArtisan265Connect to Database Via CliTo get access to your database via CLI directly, you can run the following without any parametersArtisan266Factory CallbacksWhile using factories for seeding data, you can provide Factory Callback functions to perform some action after record is inserted.Factories267Generate Images with Seeds/factoriesDid you know that Faker can generate not only text values but also IMAGES? See avatar field here - it will generate 50x50 imageFactories268Override Values and Apply Custom Login to ThemWhen creating records with Factories, you can use Sequence class to override some values and apply custom logic to them.Factories269Using Factories with RelationshipsWhen using factories with relationships, Laravel also provides magic methods.Factories270Create Models without Dispatching Any EventsSometimes you may wish to update a given model without dispatching any events. You may accomplish this using the updateQuietly methodFactories271Useful for() MethodThe Laravel factory has a very useful for() method. You can use it to create belongsTo() relationships.Factories272Run Factories without Dispatching EventsIf you want to create multiple records using Factory without firing any Events, you can wrap your code inside a withoutEvents closure.Factories273Specify Dependencies in the Run() MethodYou can specify dependencies in the run() method of your seeder.Factories274Logging with ParametersYou can write Log::info() , or shorter info() message with additional parameters, for more context about what happened.Log and debug275Log Long Running Laravel QueriesPractical Laravel guidance for log long running laravel queries, with examples and copyable PHP code.Log and debug276Benchmark ClassIn Laravel 9.32 we have a Benchmark class that can measure the time of any task. It's a pretty useful helperLog and debug277More Convenient DdInstead of doing dd($result) you can put - dd() as a method directly at the end of your Eloquent sentence, or any Collection.Log and debug278Log with ContextNew in Laravel 8.49: Log::withContext() will help you to differentiate the Log messages between different requests.Log and debug279Quickly Output an Eloquent Query in Its SQL FormIf you want to quickly output an Eloquent query in its SQL form, you can invoke the toSql() method onto it like soLog and debug280Log All the Database Queries During DevelopmentIf you want to log all the database queries during development add this snippet to your AppServiceProviderLog and debug281Discover All Events Fired in One RequestIf you want to implement a new listener to a specific event but you don't know its name, you can log all events fired during the request.Log and debug282Make Retried Jobs IdempotentQueue workers may retry work after a timeout or lost acknowledgement, even when part of the job already ran. Make repeating the same operation safe by…Reliability and Performance283Suppress Duplicate Job Dispatches with ShouldbeuniqueWhen only one queued job per resource should be pending, implement ShouldBeUnique and return a resource-specific key. Laravel uses that key to hold a cache…Reliability and Performance284Prevent Concurrent Jobs from Updating the Same ResourceUse WithoutOverlapping when two jobs may both be queued but must not modify the same resource at the same time. This is different from unique dispatch:…Reliability and Performance285Back Off Between Retries of Transient FailuresImmediate retries can overload a service that is already failing. Set a bounded retry count and increase the delay between attempts for temporary network or…Reliability and Performance286Keep Scheduled Tasks Safe Across Multiple ServersWhen every server runs Laravel's scheduler, use onOneServer() to elect one runner and withoutOverlapping() to prevent a slow execution from starting again…Reliability and Performance287Serve Stale Cache Data While Refreshing ItFor expensive values that can be briefly stale, Cache::flexible() returns a fresh value immediately and refreshes a stale value after the response. This…Reliability and Performance288API Resources: with or without "Data"?If you use Eloquent API Resources to return data, they will be automatically wrapped in 'data'. If you want to remove it, add…API289Conditional Relationship Counts on API ResourcesYou may conditionally include the count of a relationship in your resource response by using the whenCounted method. By doing so, the attribute is not…API290API Return "Everything Went Ok"If you have API endpoint which performs some operations but has no response, so you wanna return just "everything went ok", you may return 204 status code…API291Avoid N+1 Queries in API ResourcesYou can avoid N+1 queries in API resources by using the whenLoaded() method. This will only append the department if it’s already loaded in the Employee model.API292Get Bearer Token from Authorization HeaderThe bearerToken() function is very handy when you are working with apis & want to access the token from Authorization header.API293Sorting Your API ResultsSingle-column API sorting, with direction control we do the same for multiple columns (e.g., ?sort=name,-weight)API294Customize Exception Handler for APILaravel 8 and below: There's a method render() in App\Exceptions classAPI295Force JSON Response for API RequestsIf you have built an API and it encounters an error when the request does not contain "Accept: application/JSON " HTTP Header then the error will be…API296API VersioningWhen to version? If you are working on a project that may have multi-release in the future or your endpoints have a breaking change like a change in the…API297Localhost in .EnvDon't forget to change APP URL in your .env file from http://localhost to the real URL, cause it will be the basis for any links in your email notifications…Other298Time Value in the Past/futureIf you want to have some time value in the past/future, you can build it by chaining various Laravel/Carbon helpers, like now()- [add or subtract…Other299Do Some Work After a Response Has Been Sent to the BrowserYou can also use middleware to do some work after a response has been sent to the browser. Such middleware is called Terminable Middleware.Other300Redirect with URL FragmentDid you know you can add a URI fragment when redirecting to a route in Laravel? Super useful when redirecting to a specific section of the page. E.g.…Other301Use Middleware to Adjust Incoming RequestLaravel's middlewares are a great way to transform incoming requests. For example, I decided to rename a model in my application; instead of bumping the API…Other302Redirect Away from Laravel AppSometimes, you might need to redirect away from your Laravel application to other websites. In that case, there is a handy away method you can call on the…Other303Blade Directive to Show Data in Specific EnvironmentDid you know Laravel has a 'production' blade directive that you can use to show data only when you are in a production environment?Other304Schedule Laravel Job Based on Time ZoneDo you know you can schedule laravel job based on time zone Setting Timezone for One CommandOther305Use Assertmodelmissing Instead AssertdatabasemissingWhile testing model deletion, use assertModelMissing instead assertDatabaseMissing.Other306Various Options to Format Diffforhumans()In Carbon, did you know you can add various options to format diffForHumans()? Read the docs for more examples.Other307Create Custom Disks at RuntimeDid you know that you can create custom disks at runtime without the need to have the config in your config/filesystems file?Other308When (Not) to Run "Composer Update"Not so much about Laravel, but... Never run composer update on production live server, it's slow and will "break" repository. Always run composer update…Other309Composer: Check for Newer VersionsIf you want to find out which of your composer.json packages have released newer versions, just run composer outdated . You will get a full list with all…Other310Auto-capitalize TranslationsIn translation files ( resources/lang ), you can specify variables not only as :variable , but also capitalized as :VARIABLE or :Variable - and then…Other311Carbon with Only HoursIf you want to have a current date without seconds and/or minutes, use Carbon's methods like setSeconds(0) or setMinutes(0) .Other312Single Action ControllersIf you want to create a controller with just one action, you can use invoke() method and even create "invokable" controller.Other313Redirect to Specific Controller MethodYou can redirect() not only to URL or specific route, but to a specific Controller's specific method, and even pass the parameters. Use thisOther314Use Older Laravel VersionIf you want to use OLDER version instead of the newest Laravel, use this command: Change 7.\ to whichever version you want.Other315Add Parameters to Pagination LinksIn default Pagination links, you can pass additional parameters, preserve the original query string, or even point to a specific xxxxx anchor.Other316Repeatable Callback FunctionsIf you have a callback function that you need to re-use multiple times, you can assign it to a variable, and then re-use.Other317Request: Has AnyYou can check not only one parameter with $request- has() method, but also check for multiple parameters present, with $request- hasAny()Other318Simple PaginationIn pagination, if you want to have just "Previous/next" links instead of all the page numbers (and have fewer DB queries because of that), just change…Other319Blade Directive to Add True/false ConditionsNew in Laravel 8.51: @class Blade directive to add true/false conditions on whether some CSS class should be added. Read more in docsOther320Jobs Can Be Used without QueuesJobs are discussed in the "Queues" section of the docs, but you can use Jobs without queues, just as classes to delegate tasks to. Just call $this-…Other321Use Faker Outside Factories or SeedersIf you want to generate some fake data, you can use Faker even outside factories or seeds, in any class.Other322Schedule ThingsYou can schedule things to run daily/hourly in a lot of different structures. You can schedule an artisan command, a Job class, an invokable class, a…Other323Search Laravel DocsIf you want to search Laravel Docs for some keyword, by default it gives you only the TOP 5 results. Maybe there are more?Other324Filter Route:listNew in Laravel 8.34: php artisan route:list gets additional flag --except-path , so you would filter out the routes you don't want to see. See original PROther325Blade Directive for Not Repeating YourselfIf you keep doing the same formatting of the data in multiple Blade files, you may create your own Blade directive.Other326Artisan Commands HelpIf you are not sure about the parameters of some Artisan command, or you want to know what parameters are available, just type php artisan help [a command…Other327Disable Lazy Loading When Running Your TestsIf you don't want to prevent lazy loading when running your tests you can disable itOther328Using Two Amazing Helpers in Laravel Will Bring Magic ResultsUsing two amazing helpers in Laravel will bring magic results... In this case, the service will be called and retried (retry). If it stills failing, it will…Other329Request Parameter Default ValueHere we are checking if there is a per page (or any other parameter) value then we will use it, otherwise, we will use a default one.Other330Pass Middleware Directly into the Route without Register ItPractical Laravel guidance for pass middleware directly into the route without register it, with examples and copyable PHP code.Other331Transforming an Array to CssclassesPractical Laravel guidance for transforming an array to cssclasses, with examples and copyable PHP code.Other332"Upcominginvoice" Method in Laravel Cashier (Stripe)You can show how much a customer will pay in the next billing cycle. There is a "upcomingInvoice" method in Laravel Cashier (Stripe) to get the upcoming…Other333Laravel Request Exists() Vs Has()Practical Laravel guidance for laravel request exists() vs has(), with examples and copyable PHP code.Other334There Are Multiple Ways to Return a View with VariablesPractical Laravel guidance for there are multiple ways to return a view with variables, with examples and copyable PHP code.Other335Schedule Regular Shell CommandsWe can schedule regular shell commands within Laravel scheduled commandOther336HTTP Client Request without VerifyingSometimes, you may want to send HTTP request without verifying SSL in your local environment, you can do like soOther337Test That Doesn't Assert AnythingTest that doesn't assert anything, just launch something which may or may not throw an exceptionOther338"Str::mask()" MethodLaravel 8.69 released with "Str::mask()" method which masks a portion of string with a repeated characterOther339Extending Laravel ClassesThere is a method called macro on a lot of built-in Laravel classes. For example Collection, Str, Arr, Request, Cache, File, and so on.Other340Can FeatureIf you are running Laravel v8.70 , you can chain can() method directly instead of middleware('can:..')Other341Temporary Download UrlsYou can use temporary download URLs for your cloud storage resources to prevent unwanted access. For example, when a user wants to download a file, we…Other342Dealing with Deeply-nested ArraysIf you have a complex array, you can use data get() helper function to retrieve a value from a nested array using "dot" notation and wildcard.Other343Customize How Your Exceptions Are RenderedYou can customize how your exceptions are rendered by adding a 'render' method to your exception.Other344The Tap HelperThe tap helper is a great way to remove a separate return statement after calling a method on an object. Makes things nice and cleanOther345Reset All of the Remaining Time UnitsYou can insert an exclamation into the DateTime::createFromFormat method to reset all of the remaining time unitsOther346Scheduled Commands in the Console Kernel Can Automatically Email Their Output If Something Goes WrongDid you know that any commands you schedule in the console kernel can automatically email their output if something goes wrongOther347Be Careful When Constructing Your Custom Filtered Queries Using Get ParametersPractical Laravel guidance for be careful when constructing your custom filtered queries using get parameters, with examples and copyable PHP code.Other348Dust Out Your Bloated Route FileDust out your bloated route file and split it up to keep things organizedOther349You Can Send E-mails to a Custom Log FileIn Laravel you can send e-mails to a custom log file. You can set your environment variables like thisOther350Markdown Made EasyLaravel provides an interface to convert markdown in HTML out of the box, without the need to install new composer packages.Other351Simplify If on a Request with Whenfilled() HelperWe often write if statements to check if a value is present on a request or not. You can simplify it with the whenFilled() helper.Other352Pass Arguments to MiddlewareYou can pass arguments to your middleware for specific routes by appending ':' followed by the value. For example, I'm enforcing different authentication…Other353Get Value from Session and ForgetIf you need to grab something from the Laravel session, then forget it immediately, consider using session()- pull($value) . It completes both steps for you.Other354$Request->date() MethodNew in this week's Laravel v8.77: $request- date() method. Now you don't need to call Carbon manually, you can do something like: $post- publish at =…Other355Use Through Instead of Map When Using PaginationWhen you want to map paginated data and return only a subset of the fields, use through rather than map . The map breaks the pagination object and changes…Other356Quickly Add a Bearer Token to HTTP RequestThere’s a withToken method to attach the Authorization header to a request.Other357Copy File or All Files from a FolderYou can use the readStream and writeStream to copy a file (or all files from a folder) from one disk to another keeping the memory usage low.Other358Sessions Has() Vs Exists() Vs Missing()Do you know about has , exists and missing methods in Laravel session?Other359Test That You Are Passing the Correct Data to a ViewNeed to test that you are passing the correct data to a view? You can use the viewData method on your response. Here are some examplesOther360Use Redis to Track Page ViewsTracking something like page views with MySQL can be quite a performance hit when dealing with high traffic. Redis is much better at this. You can use Redis…Other361To_route() Helper FunctionLaravel 9 provides shorter version of response()- route() , take a look on the following codeOther362Pause a Long Running Job When Queue Worker Shuts DownWhen running a long job, if your queue worker gets shutdown by - Stopping the worker. - Sending signal SIGTERM ( SIGINT for Horizon). - Pressing CTRL + C…Other363Freezing Time in Laravel TestsIn your Laravel tests, you might sometimes need to freeze the time. This is particularly useful if you're trying to make assertions based on timestamps or…Other364New Squish HelperNew in Laravel from 9.7 squish helper.Other365Specify What to Do If a Scheduled Task Fails or SucceedsYou can specify what to do if a scheduled task fails or succeeds.Other366Scheduled Command on Specific EnvironmentsRunning Laravel scheduled command on specific environments.Other367Add Conditionable Behavior to Your Own ClassesYou can use the Conditionable Trait to avoid using if/else and promote method chaining.Other368Perform Action When Job Has FailedIn some cases, we want to perform some action when job has failed. For example, send an email or a notification.Other369Ignore Database When Job Has FailedIf you ever need to bypass database when a job fails, you can do one of the below things to skip database: - Set env QUEUE FAILED DRIVER with value null .…Other
Made for the love of Laravel.Copyright © Dipesh Sukhia. All Rights Reserved.