Laravel Tip💡: Generated Columns
Did you know that Laravel can handle generated columns in migrations out of the box? No need to write raw SQL in your migration to create these columns 🚀
#laravel
Laravel Tip 💡: The Conditionable Trait
Do you write multiple "if" statements to call different methods in a class? Consider making your class "conditionable" by using Laravel's "Conditionable" trait 🚀
#laravel
Laravel Tip💡: Ensure Env Keys Exist
If you want to be absolutely sure that a key exists in your .env file, use the "getOrFail()" method. It will throw a runtime exception if the key is missing. This is really useful for API keys 🚀
#laravel
Laravel Tip💡: Prevent N+1 Issues
Eager loading can significantly improve performance. Use the "preventLazyLoading" method to ensure all relationships are eager-loaded during development and customize its behavior for violations 🚀
#laravel
Laravel Tip💡: The "toQuery" method
Did you know that Laravel ships with a method called "toQuery"? This method allows you to update a collection using a single query statement by running a "whereIn" 🚀
#laravel
#php
Laravel Tip💡: The "literal" Helper
Did you know that Laravel ships with a cool helper "literal" that allows you to create a PHP object using named arguments? 🚀
#laravel
Laravel Tip💡: Hash Passwords Automatically
When creating users, we often use the Hash facade, but did you know that Laravel comes with a "hashed" cast that will automatically hash your user's password? 🚀
#laravel
Laravel Tip💡: Abbreviate Numbers
Did you know that Laravel ships with the "abbreviate" method, which allows you to format numbers in a human-readable way with an abbreviation for the units? 🚀
#laravel
Laravel Tip💡: Formatting to Percentages
Did you know Laravel ships with a "percentage" helper to get the percentage of any representative value? 🚀
#laravel
Laravel Tip💡: Validate Dates Elegantly
Did you know that when validating dates with Laravel, you can pass strings like "today" or "tomorrow" instead of actual dates? This makes the validation rules much more readable 🚀
#laravel
Laravel Tip💡: Cache Headers On The Fly
Did you know that Laravel ships with a middleware "SetCacheHeaders", which you can use to set cache headers, such as "max_age" and "etag"? 🚀
#laravel
Laravel Tip💡: Avoid Columns Ambiguity
I'm sure we've all encountered column name ambiguity when building queries at least once. To avoid that, you can use the "qualifyColumn" method, which prefixes the column with the table name 🚀
#laravel
Laravel Tip💡: Clone Your Queries
Sometimes you may need to reuse the same base query for multiple filterings. Laravel ships with a "clone" method to do exactly that 🚀
#laravel
Laravel Tip💡: Unique Request Identifiers
Have you ever needed to code a unique identifier for a request, such as for caching purposes? Laravel ships with the "fingerprint" method that allows you to generate a unique identifier for your requests 🚀
#laravel
Laravel Tip 💡: Exclude Validated Input
Sometimes, you may want to exclude an input from the validated array. Instead of manually unsetting it, you can use the "exclude" rule, which does exactly that 🚀
#laravel
Laravel Tip 💡: Filter Only Real Emails
Tired of high bounce rates from invalid emails? Laravel ships with the "dns" validation rule to ensure you get real emails. It won't magically fix the issue, but it definitely improves deliverability 🚀
#laravel
Laravel Tip 💡: The "tap" Helper
How many times have you needed to return an object right after a basic action? Yes, many times I know. The "tap" helper allows you to do just that 🚀
#laravel
Laravel Tip💡: Check If Your Model Has Changed Since Last Retrieval
Did you know Laravel ships with the `isDirty()` method, which allows you to check if one or more attributes have changed since the last time you retrieved the model? 🚀
#laravel
Laravel Tip💡: Send Concurrent Requests
Laravel's HTTP client wraps Guzzle, which allows you to make concurrent requests to speed things up. This is very helpful for various cases, such as health checks! 🚀
#laravel
Laravel Tip💡: Shape Your Strings
Since Laravel uses FakerPHP for generating fake data, you can use "lexify" to generate strings in a specific pattern 🚀
#laravel
Laravel Tip 💡: Use Default Models
When working with "hasOne" or "belongsTo" relationships, we often check whether they are nullable before accessing their properties. In such cases, you can use default models and be sure you will never get null values 🚀
#larave
Laravel Tip💡: The "latest" and "oldest" Methods
We often order models in ascending or descending order using the "orderBy" method. But did you know that Laravel comes with two methods, "latest" and "oldest," that do exactly that? 🚀
#laravel
Laravel Tip 💡: Pass Multiple IDs and Specific Columns to "find"
We often use "find()", but did you know you can pass an array of IDs and select specific columns? 🚀
#laravel
Laravel Tip 💡: Add Multiple Columns After a Specific Column
Did you know that you can add multiple columns after a specific column using the "after" method? 🚀
#laravel
Laravel Tip💡: Cast Values On The Fly
Sometimes you may need to apply casts while executing a query. Luckily, you can do that on the fly with the "withCasts" method that Laravel ships with 🚀
#laravel
Laravel Tip💡: Time Travel in Your Tests
Did you know that Laravel comes with cool time helpers that allow you to travel into the future or the past in your tests? 🚀
#laravel
Laravel Tip💡: The "valueOrFail" Method
We often use the "firstOrFail" method to get a single value from the resulting model. Did you know that Laravel ships with the "valueOrFail" method, which allows you to do exactly that? 🚀
#laravel
Laravel Tip💡: Conditionally Adding Rules
When working with dynamic forms, you might want to validate certain inputs only if another input is checked. Laravel ships with the "exclude_if" validation rule, which does exactly that 🚀
#laravel
Laravel Tip 💡: Log Out Other Devices
When users log out, you might want to ask them if they want to log out from other devices while keeping the current one. Luckily, Laravel ships with the "logoutOtherDevices" method that does exactly that. 🚀
#laravel
Laravel Tip💡: Ping URLs When Running Commands
Did you know you can ping URLs before and after your command has run? This is really useful if you want to notify an external service or a webhook. 🚀
#laravel
Laravel Tip💡: Schedule Jobs Based On Time Zones
Did you know that you can schedule jobs based on specific time zones? You can do so by chaining the "timezone" method 🚀
#Laravel
Laravel Tip💡: Generate Fake Credit Card Numbers
Since Laravel uses FakerPHP under the hood, you can generate fake credit card numbers for your tests 🚀
#laravel
Laravel Tip💡: Group Resource Controllers
Did you know that you can group resource controllers using the "resources()" method? It makes routing even cleaner! 🚀
#laravel
#php
Laravel Tip💡: The "createOr" Laravel
Sometimes, you may want to execute some actions when no record is found, beyond just creating a new instance. The "createOr" method allows you to do exactly that 🚀
#laravel
Laravel Tip💡: Invisible Columns
If you are using MySQL/MariaDB as your database, you can leverage invisible columns. These columns remain hidden in "SELECT * " statements, which is perfect for handling sensitive information and precomputed columns 🚀
#laravel
Laravel Tip💡: The "firstWhere" Method
We often need to get the first record matching a where statement. While "where()" combined with "first()" does the job, Laravel ships with a shortcut "firstWhere()" to do exactly that 🚀
#laravel
Laravel Tip 💡: Working with Base64 Strings
We often work with Base64 strings, especially when building API integrations. Laravel comes with built-in helpers to work with Base64 right out of the box 🚀
#laravel
Laravel Tip💡: Get Bearer Tokens Elegantly
Building an API with Laravel? You can retrieve the bearer token using the "bearerToken" method on the request object without having to manually parse it 🚀
#laravel
Laravel Tip💡: Work with IPs
Sometimes you may need to work with IP addresses. Laravel uses the HttpFoundation component from Symfony under the hood, which comes with useful IP helpers 🚀
#laravel
Laravel Tip💡: Exclude Middleware
Sometimes you may need to exclude a middleware from a specific route. You can do this using the "withoutMiddleware()" method 🚀
#laravel
Laravel Tip 💡: The Pipeline Helper
Often, we need to process input through multiple steps, such as applying request filters to a query or cleaning data in a multi-stage chain. When you find yourself in such cases, use Laravel's Pipeline helper 🚀
#laravel
Laravel Tip💡: The "foreignIdFor" Method
When defining foreign IDs, Laravel offers multiple methods, one of which is "foreignIdFor()". Not only does it make your code more readable, but you can quickly navigate to the model from the migration 🚀
#laravel
#php
Laravel Tip💡: Check Collection Item Types
Sometimes you may want to ensure that the collection items are all of a specific type. While "each()" paired with an "instanceof()" check might do the trick, Laravel already ships with the `ensure` method to do that 🚀
#laravel
Laravel Tip 💡: A Better Implode
We've all used PHP's "implode" function, but did you know about the "join" helper? It does the same thing but also allows you to customize the last separator 🚀
#laravel
Laravel Tip💡: Extract Validated Input
When working with validated input, we often need to extract only a few items from the request. Instead of manually unsetting or filtering, use Laravel's "safe()" method to do this elegantly 🚀
#laravel
Laravel Tip💡: Generate Random Passwords
Did you know that Laravel ships with a "password" method that generates random, strong passwords? This is helpful when you want to suggest passwords for your users 🚀
#laravel
Laravel Tip 💡: Bulk Dispatch
While Laravel offers batches to dispatch jobs, sometimes you just want to fire and forget. In that case, you can dispatch the jobs in bulk instead of individually 🚀
#laravel
Laravel Tip 💡: Safer Passwords for Users
Users tend to use the same password for all websites, which puts them in danger if their password has been leaked. You can make sure that the user inputs an uncompromised password using the "uncompromised" rule 🚀
#laravel
Laravel Tip💡: Magic Factories Methods
We use factories a lot. Did you know about the "for[Relation]" and "has[Relation]" magic methods? You just need to make sure you have the relationship set up in your model and you are good to go 🚀
#laravel
Laravel Tip💡: Skip Collection Items Until a Condition is Met
Sometimes, when working with collections, you may want to skip all the elements until a condition is met. Laravel comes with the "skipUntil" method to do exactly that 🚀
#laravel
Laravel Tip 💡: Run Seeders During Tests
Did you know you can run database seeders from within your tests? This allows you to keep your tests clean by moving setup logic to seeders 🚀
Test is written in
@pestphp
🔥
#laravel
Laravel Tip💡: The New "chopStart" and "chopEnd" Methods
Laravel 11.14 introduces 2 new string helpers that allow you to remove characters from the beginning or end of a string 🚀
#laravel
Laravel Tip💡: Save Multiple Related Models
Did you know that Laravel allows you to save multiple related models at once by using the "saveMany" method? 🚀
#laravel
#php
Laravel Tip💡: Disable Model Events When Seeding
In most cases, when seeding the database, you don't need to fire model events. You can use the "WithoutModelEvents" trait to mute those events, making your seeders slightly faster 🚀
#laravel
Laravel Tip💡: Task Hooks
Did you know that Laravel allows you to define callbacks to be executed based on the result of a scheduled task? This helps log failures or execute related actions on success 🚀
#laravel
#php
Laravel Tip 💡: Auto Capitalize Your Translations
Did you know that not only can you parameterize your translation strings, but you can also auto-capitalize them? 🚀
#laravel
Laravel Tip💡: Human-readable Numbers
Sometimes you may want to format numbers for your users in a human-readable format. The "Number" helper allows you to do just that 🚀
#laravel
Laravel Tip💡: The "containsOneItem" Method
Sometimes we want to ensure a collection has a single item. Instead of calling the count method on the collection, there is an elegant method called "containsOneItem" that does the same 🚀
#laravel
Laravel Tip💡: Custom Route Model Binding Resolution
Laravel's route model binding is a powerful feature that automatically injects your model into your controller. If you wish, you can implement custom logic for resolution by defining "resolveRouteBinding" 🚀
#laravel
#php
Laravel Tip💡: The "Sleep" Helper
Did you know that Laravel ships with a fluent wrapper for the PHP "sleep" method? This not only makes the code readable but also testable, as you can fake the Sleep class 🚀
#laravel
Laravel Tip💡: The "data_get" Helper
When working with nested arrays, Laravel provides a cool helper called "data_get". This helper allows you to use dot syntax and wildcards to retrieve values 🚀
#laravel
Laravel Tip💡: Swap Multiple Strings
When working with strings, we often need to find and replace occurrences of multiple strings. Laravel ships with an elegant method "swap" to do exactly that 🚀
#laravel
Laravel Tip💡: Find Many
Did you know you can pass multiple IDs to the "find()" method? Laravel also ships with a slightly more readable version, "findMany()", which does the same thing! 🚀
#laravel
Laravel Tip💡: Delete (Destroy) Records
Did you know that Laravel ships with the "destroy" method, which allows you to delete records by their primary key? 🚀
#laravel
Laravel Tip💡: Type Hinting for Blade
We use Blade a lot, and if I have one thing to complain about, it's type hints. However, we can solve this issue by defining a "
@php
" block for all the variables used 🚀
#laravel
Laravel Tip💡: Hook into Authentication Events
Did you know that the Laravel authentication component comes with multiple events you can listen to? Whether a user attempts to log in or fails to do so, you can handle these events as you wish 🚀
#laravel
Laravel Tip💡: Customize the Redirect Location
We often use form requests for validation. Did you know you can customize the redirect location upon failure? You are never limited to redirecting users back to the previous page 🚀
#laravel
Laravel Tip💡: The "withExists" Method
Did you know that Laravel ships with a method called "withExists" which allows you to check if a model has a relationship or not? 🚀
#laravel
Laravel Tip💡: Shortcuts for Dropping Columns
Need to drop some framework-specific columns? You don’t have to specify them manually, Laravel provides shortcuts to do exactly that 🚀
#laravel
Laravel Tip💡: HTTP Client Handler Stats
The Laravel HTTP Client uses Guzzle under the hood, providing access to statistics for each request you make. That includes total time, download speed, and much more 🚀
#laravel
Laravel Tip 💡: Formatting to a Human-Readable File Size
Did you know Laravel ships with a "fileSize" helper to get the file size representation of a given byte value as a string? 🚀
#laravel
Laravel Tip 💡: Cache Accessor Result
When working with accessors, objects are cached by default. However, if you have a computationally intensive accessor for a primitive value, like a string, you can enable caching for it using the "shouldCache()" method 🚀
#laravel
Laravel Tip💡: Clean Up After Failed Jobs
When jobs fail, you may want to send notifications or perform some cleanups. Luckily, Laravel allows you to define a "failed" method to do exactly that 🚀
#laravel
Laravel Tip💡: Filter Null Values
When working with arrays, we sometimes need to filter out null values. Laravel ships with an elegant helper "whereNotNull" to do exactly that 🚀
#laravel
Laravel Tip💡: Randomly Order Query Results
Did you know that Laravel comes with the "inRandomOrder" method, which sorts query results randomly? 🚀
#laravel
#php
Laravel Tip💡: Lazily Refresh Your Database
We often need to refresh the database when testing the code. In such cases, you can lazily refresh your database, so migrations are run only when you are hitting the db. This will help speed up your tests 🚀
#laravel
Laravel Tip 💡: Better Error Messages for Arrays
When validating arrays, it's a better UX to tell the user which item has failed rather than throwing a generic message. For this, you can use the ":index" and ":position" placeholders 🚀
#laravel
Laravel Tip 💡: Freeze Time
When writing tests, we sometimes need to "freeze" time to make assertions. Laravel provides an elegant method "freezeTime" to do exactly that 🚀
#laravel
Laravel Tip💡: Run Commands In the Background
Scheduled commands run sequentially. If you have a long-running task, it could take longer than anticipated and cause a delay for other tasks. Luckily, in such cases, you can use the "runInBackground" method 🚀
#laravel
Laravel Tip💡: Truncate Long Strings
Sometimes you may want to truncate long descriptions for display. Laravel ships with the "limit" method to do just that, and in the upcoming version, you can preserve whole words for a better UX 🚀
#laravel
Laravel Tip💡: Log Out The Current Device Only
Did you know that Laravel ships with the "logoutCurrentDevice" method, which allows you to log out only the currently authenticated device? 🚀
#laravel
Laravel Tip💡: Make Use Of Factory States
Did you know that Laravel factories allow you to define states? You can use multiple states to describe the object and apply discrete modifications to it. This also makes the code more readable! 🚀
#laravel
PHP Tip💡: Much Readable Numbers
If you work with numbers, the longer they are, the harder they get to read. Did you know you can use underscores for better readability? 🚀
#laravel
Laravel Tip 💡: Execute Tasks Concurrently
Starting from Laravel v11.23, you can execute tasks concurrently. This can speed things up when you have independent tasks that can be run simultaneously 🚀
#laravel
Laravel Tip 💡: On-Demand Notifications
Sometimes, you may want to send notifications to "anonymous" users who are not yet stored in the database. Laravel's "route" method allows you to do exactly that 🚀
#php
#laravel
#webdevelopment
#tipsandtricks
Laravel Tip💡: The "rescue" Helper
Sometimes we are forced to use a try-catch block just to ignore an expected exception and default to a value. In such cases, you can use the "rescue" helper that Laravel ships with🚀
#laravel
#php
Laravel Tip💡: The "throw_if" and "throw_unless" Helpers
Did you know that Laravel ships with two helpers, "throw_if" and "throw_unless," which not only make your code shorter but also much more readable? 🚀
#laravel
Laravel Tip💡: Better Checks For Input Presence
We often need to check if a request contains certain values. Did you know that Laravel ships with two cool methods, "has" and "hasAny", to perform these checks elegantly? 🚀
#laravel
Laravel Tip💡: Mask Strings
Ever found yourself in need of masking an email or a verification code for security purposes? Laravel ships with the "mask" method to do exactly that! You can always combine it with other methods to avoid leaking the length of the string 🚀
#laravel
Laravel Tip 💡: The "checked" Blade Directive
Often, we need to conditionally mark an input as checked. While this can be done manually, Laravel provides a cool blade directive "checked" to do exactly that 🚀
#laravel
Laravel Tip💡: The "sole" Method
When working with collections, whether regular or Eloquent, if you want to get the first item that matches the condition and ensure it is the only one, use the "sole" method 🚀
#laravel
Laravel Tip💡: Insert Or Ignore
Sometimes, you might want to ignore errors when inserting data. Laravel comes with the "insertOrIgnore" method that does exactly that 🚀
#laravel
Laravel Tip💡: Bootable Traits
Did you know that Laravel automatically boots your traits if they follow the "boot[TraitName]" convention? This allows you to easily define shared logic for model events. And here's a secret: that's where multi-tenancy starts 🚀
#laravel
Laravel Tip💡: Faster Queries with "whereIntegerInRaw"
When using a whereIn query with non-user input, opt for whereIntegerInRaw. This speeds up your query by skipping PDO bindings and Laravel's security measures against SQL injection 🚀
#laravel
Laravel Tip💡: The "whenTableDoesntHaveColumn" and "whenTableHasColumn" methods
Laravel 9 and onward ships with 2 schema methods, 'whenTableDoesntHaveColumn' and 'whenTableHasColumn', which allow you to drop or create a column if it exists or not.
#laravel
#php
Laravel Tip💡: The "Benchmark" Helper
Did you know that Laravel 9.32 and above comes with a handy helper called "Benchmark" that allows you to measure the number of milliseconds it takes for the given callbacks to complete? 🚀
#laravel
Laravel Tip💡: The "last" and "head" helpers
Did you know that Laravel ships with two helpers, "last" and "head"? They allow you to retrieve the first and last elements of an array 🚀
#laravel