Posts about "Laravel"

Quickly inspect the database and its tables in Laravel

— It’s sometimes convenient if you can quickly glance over the database your Laravel application is using and its tables. This is especially useful when you’re working on a legacy project and you’re not sure about the database structure.

APA-style titles in Laravel

— APA-style titles are a specific type of title case that is used in academic papers, research reports, and journal articles. It’s a style that’s used by the American Psychological Association (APA) and is a variation of the title case.

Using arrays as a lightweight database in Laravel

— There are times when you don’t want to use a full-fledged database like MySQL or PostgreSQL for your application. For instance, if you’re building a small application that relies heavily on reading small subset of data, you might not want to setup a database table for something like that.

Auto-generate maintenance mode secret in Laravel

— Maintenance mode is a feature in Laravel that allows you to put your application down for maintenance. It’s a great way to inform your users that the application is down for maintenance and will be back up soon.

Using any large JSON as a lazy collection in Laravel

— If you’re working with Laravel (or any PHP application for that matter), you might have stumbled upon a situation where you need to process a large JSON input. For instance, you might want to use a JSON file to seed your database.

Artisan command to generate views in Laravel

— Laravel has all kinds of Artisan commands to let you generate boilerplate code for your application. For instance, you can generate a controller, model, migration, and so on using the Artisan command. But, there was no command to generate views in Laravel until now.

The many ways to tail the application log in Laravel

— Jeffery Way recently tweeted about how he wants a php artisan tail command to see the real-time application logs in Laravel. And the replies to this tweet were quite interesting. People have shared their ways of tailing the Laravel log. So, I thought to compile them all in one place.

Eloquent Strict Mode in Laravel

— Laravel’s Eloquent is a pretty powerful ORM. It allows you to seamlessly interact with your database tables using a simple and expressive syntax. But sometimes, it can be a little too forgiving about the mistakes you make while interacting with the database.

Using beautiful command prompts in Laravel

— Artisan commands in Laravel are truly a blessing. I mean you could create just about any files be it controllers, models, middleware, or provider by knocking a simple command from the CLI.

Ensure type uniformity of a collection in Laravel

— Sometimes, you may want to ensure that a collection in Laravel contains only a specific type of item. For instance, you may want to ensure that a collection contains only a string type of item. Or, you may want to ensure that a collection contains items of a specific class.

Global HTTP middleware in Laravel 10.x

— Sometimes when working with third-party APIs, there might be a need to add common headers to all the outgoing requests. For instance, you might want to add an Authorization header to all the outgoing requests to authenticate the requests.

Rollback a specific migration in Laravel

— There comes a time when you want to make some changes to an existing table. For instance, you want to change the data type of a column. So, in this case, you can modify the migration file of the table and then run the migration again using the artisan migrate:refresh command like so.

Dynamic URLs with URI templates in Laravel

— There comes a time when you want to make HTTP requests but the URL using which you want to make the request is dynamic. For example, you want to make a request to the GitHub API to get the details of a user but the username is dynamic. Or the version of the API is dynamic.

The new helper to generate secure passwords in Laravel 10.x

— Oftentimes, you may need to generate a secure password for your users. And in such cases, you may use the Str::random() method to generate a random string. But, the problem with this method is that it generates a random string that may not be secure enough.

File validation rule object in Laravel 9.x

— Validating things plays a crucial role in any web application. In Laravel, you can validate the incoming request data using the validate() method. This method accepts an array of validation rules as its first argument. These rules are used to validate the incoming request data.

Rendering specific fragment of a blade view in Laravel 9.x

— Blade views are the most common way to render HTML in Laravel. But, what if you want to render a specific fragment of a blade view? For instance, you want to render a specific section of a blade view. Or, you want to render a specific component of a blade view.

The new alternative mailable syntax in Laravel 9.x

— The latest version of Laravel 9.x has just been released and it comes with a lot of new features and improvements. In this article, I’ll talk about one of the new features in Laravel 9.x which is the new alternative mailable syntax.

Encrypting and decrypting environment files in Laravel 9.x

— The use of environment files in Laravel (or any other similar framework) is pretty common. You can use the .env file to store the environment variables. This is a great way to store sensitive information like API keys, database credentials, etc. in a secure way.

The global faker helper in Laravel 9.x

— How many times does this happens to you that when you’re building UIs, you add placeholders (“Lorem Ipsum”, “John Doe”, etc..) to the places where it needs data from database or external APIs?

Plural strings based on the count in Laravel

— Working with strings can prove to be tricky in some scenarios. For instance, when building a cart for an eCommerce website, you may need to show the string “item” in singular/plural form based on how many items are there in the cart.

How to validate JSON in Laravel

— I’m pretty sure if you’re older enough to be working in the software development industry, the one format that you would be working with in a recurring manner is JSON.

The new findOr method in Laravel 9.x

— A minor release for Laravel 9.x dropped a few days ago and among lots of new features and improvements, this release has introduced a new method called findOr in the Eloquent Builder and Relations.

New undot() and reverse() methods in Laravel 8.x

— Some may argue that Laravel is a framework that is bloated with methods and stuff to do everything under the sun. But in my opinion, that’s one of those things that make Laravel, “Laravel” because the more options you have out of the box, the better your life gets!

Mask part of a string in Laravel 8.x

— There comes a time when you would be in need of obfuscating a certain part of the string. For instance, to obfuscate the credit card’s digits except the last four or to mask specific parts of the phone number or email.

Getting subsets of validated data in Laravel 8.x

— Laravel offers mainly two ways to validate the request data inside of the controller methods. Either you can directly call the validate method on the Illuminate\Http\Request object and set the validation rules or you can create a form request and type-hint the controller method with this form request class.

The prohibited validation rule in Laravel 8.x

— Sometimes, all you would need is to forcefully prevent some of the fields in the request. Essentially, to “prohibit” or ban the fields to be mandatorily empty or not present in the request at all.

Tappable and pipeable fluent strings in Laravel 8.x

— The fluent string operations were introduced back in the release of Laravel 7 which offered a more object-oriented, fluent string manipulation library built on top of Illuminate\Support\Str functions. To use this fluent API, you’d need to use the Illuminate\Support\Str::of method which creates a fluent Illuminate\Support\Stringable object.

Retry operations with high probability of failure in Laravel

— There are certain operations that can have a high probability of failure. For instance, sending a request to a third-party API. You’re not sure whether it will work every time flawlessly because it’s not in your control. If the API endpoint you’re hitting is not responding, you might end up with an exception straight away.

A little known artisan command that can inspire you

— While working on your codebase, be it developing features for your application or fixing bugs, we all tend to get a little bit demotivated sometimes in the middle of those sessions. Because after all, we are all humans and we all need some kind of inspiration every now and then.

How to prevent overlapping of jobs in Laravel

— When you are using Laravel queues, you might bump into the situation where you want to prevent overlapping of jobs that handles sensitive information. This could be to provide data integrity of important information such as the user’s wallet balance.

List scheduled commands in CLI in Laravel 8.x

— Sometimes, it would be convenient if you get details regarding things right in your terminal. Take for instance, all your scheduled commands that you have defined in your application’s App\Console\Kernel class’ schedule method like so.

Monitor logs in Laravel Telescope in production environment

— The Laravel Telescope package is great for debugging your application when you’re working on your application in the local environment. It provides insight into the requests coming into your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and various other things in this beautiful interface.

Using MySQL explain for queries in Laravel 8.x

— MySQL’s EXPLAIN statement is a handy tool if you want to take a quick glance over queries and to make out what’s wrong with them. Essentially, EXPLAIN is used to obtain a query execution plan (that is, an explanation of how MySQL would execute a query).

Simple and lightweight scaffolding using Breeze in Laravel 8

— When Laravel 8 released, It came with a lot of new features & improvements but along with it, the Laravel team has also introduced Jetstream for application scaffolding which comes with all the bells and whistles in-built such as login, registration, email verification, two-factor authentication, session management, API support via Laravel Sanctum, and optional team management.

How to use .env values in Laravel Envoy

— Laravel Envoy is a great tool if you want to create deployment flow for your application or even something as small as writing a script to pull the latest code and deploy the application right away.

Laravel Ecosystem Jargon

Laravel, as a framework, has grown slowly but strongly since its inception and so is its ecosystem. The ecosystem here is all the packages/products that are built by the Laravel team which revolves around the original Laravel framework. This includes open-source packages and premium/paid products.

Class based model factories in Laravel 8

— The model factories in Laravel are a great way of seeding some fake data in the database for testing purposes which I’ve discussed in this article. While the previous implementation was great, Laravel 8 has given model factories a major overhaul and it makes them even better!

Using simple yet effective caching for Laravel queries

— You know it’s always a good idea to have something at your disposal using which you can improve the performance of your applications. When it comes to web applications, one of the many things that power them is database queries and that’s why it’s no surprise that you may want to optimize those and make your application a little faster!

Tracking model attribute changes in Laravel

— Sometimes, it’s useful to know if somethig has been changed in the model since it’s been loaded. For instance, you would want to check if the is_published attribute of the Post model is set or not before publishing the post further.

Validating Laravel requests using rule objects

— Laravel comes with a multitude of ways to validate request parameters. For instance, you could use Illuminate\Http\Request’s validate method where you can specify all the fields that you would want to get validated inside controller’s action. You can do it like so.

Customizable artisan stubs in Laravel 7

— Artisan commands in Laravel are truly a blessing. I mean you could create just about any files be it controllers, models, middleware, provider by knocking a simple command from the CLI. For instance, if you want to create a model named Post you could just fire the following command…

Fluent string operations in Laravel 7

— Laravel 7 has been a major version that’s been released last week and it comes with the host of features and improvements to the Laravel framework. One of the improvements being the new fluent string operations API. The goal of these API is to provide more flexibility and readablity to the regular string operations in Laravel by chaining array of string manipulation methods.

Convert request parameters to boolean in Laravel

— Sometimes, you might want to convert some of the request parameters to boolean. For instance, take a checkbox field. Unless and until, it hasn’t been checked it won’t be passed through to the request. In such a case, it would be beneficial to convert such inputs to boolean.

Add view within another view in Blade Laravel

— Sometimes, all you need to do is to add a Blade view into an another view. For instance, when you want to add JavaScript and CSS files as a separate Blade files which will contain the related content respectively. So, maybe you’ve a JavaScript blade file called view-js.blade.php which wraps the JS code within <script> tag and a CSS blade file called view-css.blade.php which wraps the CSS code within <style> tag. And all you want to do is add these to an another blade file called view-show.blade.php.

Global view data for all actions in Laravel Blade

— Laravel’s Blade is a great templating system that blends with Laravel’s ecosystem very well. Setting some data to the view is a breeze and rendering those data into the template is ever so easy. For instance, if you would like to share some data from a controller’s action to a view, you’d do like so.

Add additional attributes in request in Laravel

— Sometimes, you might want to attach additional attributes to the original request that has made to the Laravel application. For instance, you want to put your own check in the middleware to see if the user is permitted to access the page or not, and pass that “check” by attaching it as an additional attribute to the request.

Using objects as arrays (with a real world example) in PHP

— Sometimes, it’s convenient when you could get to access class objects as arrays. For instance, the time when one of the class properties is of type array and you want to manipulate it just like you’d do with an array without exposing it during object creation. I’ve included a real world example of where this could be useful, at the end of the article. So, read on!

Attach, detach and sync many-to-many relationships in Laravel

— There exists four types of relationship associated between models/entities. And they are: One To One, One To Many, Many To One and Many To Many. We’re specifically going to talk about Many To Many relationship and most importantly attach, detach and sync helper methods that are provided in Laravel in this article.

Extending class behaviour in Laravel using Macros

— In this article, I’m going to discuss about the feature in Laravel using which you can extend the functionality of certain Laravel’s core classes without even touching the original codebase. Or in other words, adding methods to the class dynamically.

Adding password confirmation on certain routes in Laravel

— If you’ve used some well creafted web application, such as GitHub for instance, you might’ve noticed that upon saving sensitive information such as settings or payment details, it asks for the password confirmation before performing the action. This adds the extra layer of security and certainly a nice-to-have feature.

How to utilize Capsule to use Eloquent ORM outside Laravel

— If you love the Laravel as a framework or more specifically its Eloquent ORM like I do then there’s a great chance that you’d like to use this great ORM in your non-Laravel PHP apps as well. And the good news is it’s rather easier than you might think. Laravel provides a standalone pacakge called Capsule which you can use in your own project. It’s a full database toolkit for PHP, providing an expressive query builder, ActiveRecord style ORM, and schema builder. It currently supports MySQL, Postgres, SQL Server, and SQLite.

Using Lazy Collections on memory-hungry operations in Laravel 6

— Laravel team has recently released v6.0 of the framework and with this they have added a bunch of exciting new features. Among which, I’m going to talk about Lazy Collections in this article. In Laravel, Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data. In face, all the Eloquent queries are always returned as Collection instances. LazyCollection essentially extends the features of the Collection class. Let’s talk about them in detail.

Process model records in chunks in Laravel

— In this tweet, Freek Van der Herten explains how to process chunk of records from a model instead of loading all of them at a time which can help using less memory. Learn more about it in the article.

Rate limit route requests in Laravel

— As backend developers, to make our web application full proof we need to make sure our application is running as efficiently as possible all the time. Otherwise, everyone using your database will suffer from slow performance. API limiting, which is also known as rate limiting, is an essential component of Internet security, as DoS attacks can tank a server with unlimited API requests.

Logout from every devices except the currently logged in one in Laravel

— Every robust web app has this feature where you’re provided with a setting through which you can choose to logout from all the devices you’ve been logged in from previously, except the current one. This is certainly a nice security feature that you can provide to your user without them even asking for it and if your app is built on top of Laravel 5.6, this comes out-of-the-box.

Attribute casting in Laravel Eloquent

— Laravel’s Eloquent is without a doubt a great ORM exists right now. It has some of the features which makes it ahead of its competitions. One such feature the ORM provides is called “Attribute casting”.

Implement Invite-only registrations using Laravel's signed URLs

— There comes a time when you want URLs which are public but still you want some kind of authentication onto the same. For instance, you’d want such kind of URLs to enable invite-only registrations for your applications, where you’d send a URL to the user which that specific person only can access and register. In such scenarios, signed URLs can come in handy which are the special kind of URLs that have a “signature” hash appended to the query string to verify that the URL has not been modified since it was created.

Packages to make your Laravel development experience awesome.

— While developing applications(not necessarily with Laravel), you come across the situation where you need to implement certain functionality. In such cases you shouldn’t want to reinvent the wheel if the functionality is been implemented by someone as a package, accepted well by the community and is ready to be consumed. It’s a no-brainer. I use to follow the same approach and today in this article, I’m going to list out some of my favorite Laravel packages which have made my experience with development in Laravel delicious.

Why you should use Laravel Queues

— There comes times when you wouldn’t want your end users staring at white screens or that intimidating loaders for a long time. For instance when user registers to your site, you must have configured your website to send a welcome email or a confirmation email upon registering. So, that operation should be snappy and for that purpose you’d actually want to reduce the amount of time your app takes while sending the email to the user. Laravel Queues comes to the recue for achieving such kind of time consuming tasks.

Laravel - Accessors & Mutators

— Accessors and mutators allow you to format Eloquent attribute values when you retrieve or set them on model instances. I’ll explain how you can you use them into your app.

Laravel Eager Loading - load() Vs. with()

— Today, while working with one of my projects(which is built on top Laravel) I bumped into the situation where I needed to get associated model’s data for one of the models. So here, I had two approaches in Laravel to accomplish this which are basically called Eager Loading: