TOPIC COLLECTION
Other.
A collection of 73 practical ideas to make everyday Laravel work a little smoother.
73 TIPS01Localhost 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…Other02Time 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…Other03Do 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.Other04Redirect 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.…Other05Use 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…Other06Redirect 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…Other07Blade 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?Other08Schedule Laravel Job Based on Time ZoneDo you know you can schedule laravel job based on time zone Setting Timezone for One CommandOther09Use Assertmodelmissing Instead AssertdatabasemissingWhile testing model deletion, use assertModelMissing instead assertDatabaseMissing.Other10Various Options to Format Diffforhumans()In Carbon, did you know you can add various options to format diffForHumans()? Read the docs for more examples.Other11Create 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?Other12When (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…Other13Composer: 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…Other14Auto-capitalize TranslationsIn translation files ( resources/lang ), you can specify variables not only as :variable , but also capitalized as :VARIABLE or :Variable - and then…Other15Carbon 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) .Other16Single Action ControllersIf you want to create a controller with just one action, you can use invoke() method and even create "invokable" controller.Other17Redirect 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 thisOther18Use Older Laravel VersionIf you want to use OLDER version instead of the newest Laravel, use this command: Change 7.\ to whichever version you want.Other19Add 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.Other20Repeatable 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.Other21Request: Has AnyYou can check not only one parameter with $request- has() method, but also check for multiple parameters present, with $request- hasAny()Other22Simple 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…Other23Blade 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 docsOther24Jobs 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-…Other25Use Faker Outside Factories or SeedersIf you want to generate some fake data, you can use Faker even outside factories or seeds, in any class.Other26Schedule 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…Other27Search 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?Other28Filter 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 PROther29Blade 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.Other30Artisan 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…Other31Disable Lazy Loading When Running Your TestsIf you don't want to prevent lazy loading when running your tests you can disable itOther32Using 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…Other33Request 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.Other34Pass 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.Other35Transforming an Array to CssclassesPractical Laravel guidance for transforming an array to cssclasses, with examples and copyable PHP code.Other36"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…Other37Laravel Request Exists() Vs Has()Practical Laravel guidance for laravel request exists() vs has(), with examples and copyable PHP code.Other38There 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.Other39Schedule Regular Shell CommandsWe can schedule regular shell commands within Laravel scheduled commandOther40HTTP Client Request without VerifyingSometimes, you may want to send HTTP request without verifying SSL in your local environment, you can do like soOther41Test That Doesn't Assert AnythingTest that doesn't assert anything, just launch something which may or may not throw an exceptionOther42"Str::mask()" MethodLaravel 8.69 released with "Str::mask()" method which masks a portion of string with a repeated characterOther43Extending 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.Other44Can FeatureIf you are running Laravel v8.70 , you can chain can() method directly instead of middleware('can:..')Other45Temporary 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…Other46Dealing 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.Other47Customize How Your Exceptions Are RenderedYou can customize how your exceptions are rendered by adding a 'render' method to your exception.Other48The 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 cleanOther49Reset All of the Remaining Time UnitsYou can insert an exclamation into the DateTime::createFromFormat method to reset all of the remaining time unitsOther50Scheduled 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 wrongOther51Be 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.Other52Dust Out Your Bloated Route FileDust out your bloated route file and split it up to keep things organizedOther53You 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 thisOther54Markdown Made EasyLaravel provides an interface to convert markdown in HTML out of the box, without the need to install new composer packages.Other55Simplify 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.Other56Pass 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…Other57Get 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.Other58$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 =…Other59Use 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…Other60Quickly Add a Bearer Token to HTTP RequestThere’s a withToken method to attach the Authorization header to a request.Other61Copy 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.Other62Sessions Has() Vs Exists() Vs Missing()Do you know about has , exists and missing methods in Laravel session?Other63Test 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 examplesOther64Use 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…Other65To_route() Helper FunctionLaravel 9 provides shorter version of response()- route() , take a look on the following codeOther66Pause 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…Other67Freezing 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…Other68New Squish HelperNew in Laravel from 9.7 squish helper.Other69Specify What to Do If a Scheduled Task Fails or SucceedsYou can specify what to do if a scheduled task fails or succeeds.Other70Scheduled Command on Specific EnvironmentsRunning Laravel scheduled command on specific environments.Other71Add Conditionable Behavior to Your Own ClassesYou can use the Conditionable Trait to avoid using if/else and promote method chaining.Other72Perform 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.Other73Ignore 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