How to Check “if not null” with Laravel Eloquent

To check “if not null” with Laravel Eloquent, you can use the whereNotNull() method. The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull() method that allows us to verify if a specific column’s value is not NULL. For instance, let’s say you have a products table, and you want to … Read more

How to Fix Laravel: PHP Parse error: syntax error, unexpected ‘?’

Laravel: PHP Parse error: syntax error, unexpected ‘?’ in /vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 500 error occurs when you are using an older version of PHP. The main reason for the error is that the “?” character is used in PHP for null coalescing (??), and it is a part of nullable type hints. Both features were … Read more

How to Format Currency in Laravel [3 Ways]

Here are three ways to format currency in Laravel. Using PHP’s number_format() Using Laravel’s Localization Using third-party package Diagram Method 1: Using PHP’s number_format() Laravel Framework is built upon PHP language, so you can format currency using PHP’s number_format() function. To properly integrate number_format(), you need to register the function in AppServiceProvider.php like this: <?php … Read more

How to Fix Composer update memory limit in PHP or Laravel

This reminds me of when I was working on an outdated Laravel project and needed to upgrade the Laravel and related dependencies.  To upgrade the dependencies, I encountered this error: “Composer update memory limit”. The memory limit error occurs during a composer update (or other Composer commands) because Composer can sometimes require a lot of … Read more

How to Comment in the .env File in Laravel

To comment in the .env file, use the “hash(#) symbol”. The interpreter interprets anything written after the hash # symbol as a comment in .env files. For example, laravel’s env file looks like this:  APP_NAME=Laravel APP_ENV=local APP_KEY=base64:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx APP_DEBUG=true We can add comments on separate lines by starting the line with a “hash # symbol.” # … Read more

How to Fix Could not open input file: artisan in Laravel

Could not open input file: artisan error occurs in Laravel when you run the artisan command outside the project’s root directory. The artisan file should be located in the root directory. To fix the error, ensure you are in the root directory of your Laravel project when running the artisan command. Common reasons and solutions Here … Read more

How to Check If a Record Exists with Laravel Eloquent

Here are four ways to check if a record exists with Laravel Eloquent. Using the exists() Method Using the first() or firstOrFail() Methods Using the count() Method Using the find() Method Method 1: Using the exists() Method The easiest way to check if a record exists in Laravel is to use the exists() method. The exists() … Read more

How to fix Unchecked runtime.lastError: The message port closed before a response was received

An error Unchecked runtime.lastError: The message port closed before a response was received occurs from Chrome browser extensions when a background process or script in a browser extension did not respond in time or was terminated before it could complete its task. The issue occurred when I was using Vue.js and Laravel for my project.  … Read more

How to Rollback a Specific Migration in Laravel

To rollback a specific migration in Laravel, “pass the –step argument to the migrate:rollback command.” Here’s how to rollback the last batch of migrations by one step: Navigate to your Laravel project root directory. Run the following command: php artisan migrate:rollback –step=1 The –step option allows you to specify how many batches of migrations you … Read more

How to Create Multiple Where Clause Query Using Laravel Eloquent

In Laravel Eloquent, you can chain multiple where clauses together to create a query with multiple conditions. Each where clause you append will be treated as an AND condition. Here’s a basic example of how you can do this: $users = User::where(‘age’, ‘>=’, 18) ->where(‘account_type’, ‘=’, ‘premium’) ->where(‘status’, ‘=’, ‘active’) ->get(); This would generate a … Read more

How to Remove a Package from Laravel using Composer

Here is the step-by-step guide to remove a package from Laravel using Composer. Remove the package declaration from the composer.json file (in the “require” section). Use the “composer remove” command. Remove Service Provider from app/config/app.php file. Remove any Class Aliases from the app/config/app.php file. Run migrations (if necessary). Clear cached configurations. Check for remaining references. … Read more

How to Get Timesince or Time ago in Laravel 10

In Laravel 10, you can use the Carbon library to get the timesince or time ago. Carbon is a popular library for working with dates and times in PHP. Example <?php use Carbon\Carbon; // Example timestamp $timestamp = ‘2022-02-28 10:00:00’; // Get the time since the timestamp $timeSince = Carbon::parse($timestamp)->diffForHumans(); // Get the time ago … Read more

How to Create Word Document File in Laravel

To create a Word document file in Laravel, use the “phpoffice/phpword” package. PHPWord is a library written in pure PHP that provides classes to write to and read from different document file formats. Here are the ways to create a Word document file in Laravel: Step 1: Install Laravel Project composer create-project –prefer-dist laravel/laravel laravelworddocument … Read more

Laravel Collection search() Method

Laravel search() is a built-in collections method “used to search the collection for a given value.” If the value is present in the collection, the key of the value is returned. If the value does not match any item, a false is returned. The search uses the “loose” comparison, meaning the string with the integer … Read more

How to Use filter For a Collection in Laravel

Laravel collection filter() method is “used to filter the collection using the given callback, keeping only those items that pass a given truth test.” Syntax public function filter(callable $callback = null) { if ($callback) { return new static(Arr::where($this->items, $callback)); } return new static(array_filter($this->items)); } The filter function takes a callback as an argument and runs a filter … Read more

Laravel MongoDB CRUD Operation Tutorial

To use Laravel with MongoDB, use the “jenssegers/mongodb” package. Configure the Mongodb database on Windows. If you connect the MongoDB database to Laravel or any PHP application, you might face one issue, the PHP MongoDB driver. The package we will install in Laravel requires the php mongodb driver installed on our machine. But suppose you … Read more

How to Integrate Elasticsearch in Laravel Application

To use Elasticsearch in Laravel, use the “Elasticquent” package. Elasticquent makes working with Elasticsearch and Eloquent models easier by mapping them to Elasticsearch types. You can use the default settings or define how Elasticsearch should index and search your Eloquent models right in the model. The Elasticquent allows you to take an Eloquent model and … Read more

Laravel Route Groups [Step-by-step Guide]

Laravel route groups allow you to organize routes that share attributes, such as path, name, or middleware. This will enable you to avoid defining these attributes on each route. These shared attributes can be passed in the array format as the first argument to the Route::group() function. For example, if you want to apply a … Read more

How to Create Multilingual Website using Laravel Localization

Laravel’s localization features provide a convenient way to retrieve strings in various languages, allowing us to support the multiple languages within your application quickly. Language strings are stored in the files within the resources/lang directory. In addition, there should be a subdirectory for each language supported by the application within that directory. We will create … Read more

How to Deploy Laravel Project on Heroku

To deploy a laravel project on Heroku from scratch, follow these steps: Install Heroku CLI. Install the Laravel. Create a proc file. Initialize git repo. Logging into the Heroku terminal. Create a Heroku app. Set up the Laravel encryption key. Push Laravel changes to Heroku. Then, configure the Database on Heroku. Add the project files … Read more

Laravel Bootstrap Modal Form Validation

To create a bootstrap modal form validation in Laravel, use the simple Ajax form validation using a bootstrap modal. The server checks all the input fields against specified validation, and if any of the validation breaks, it will redirect to our create page with error messages. Here are the steps to use bootstrap modal form … Read more

How to Create Comment Nesting in Laravel

To create a comment nesting in Laravel, use the “Polymorphic relationship.” A one-to-one polymorphic relationship is a case where one model can belong to more than one type of model but on only one association. For example, multiple comments belong to multiple users, and a comment can have multiple replies. Here are the steps to … Read more

Laravel One to One Relationship [Step-by-step Guide]

Laravel one-to-one relationship is a very basic type of relationship. An example of such a relationship could be a User and Passport model. In this case, a user is only allowed to have one passport. Thus, we have a one-to-one relationship between users and passports. To define a one-to-one relationship, you can use the hasOne … Read more

How to Integrate Admin Template in Laravel

To integrate an admin template in Laravel, download the admin panel template in plain HTML and then create a master file which is a layout file consisting of a header, content, and footer file, and then cover all the other themes files with this master file. Here is the step-by-step guide to integrating the admin … Read more

How to Use Guzzle HTTP Client Request in Laravel

To use Guzzle HTTP Client request in Laravel, use the “gurzzlehttp/guzzle” package. A Guzzle is a PHP HTTP CLIENT that we use to send HTTP requests for trivial integration with web services, such as: PATCH PUT GET DELETE POSTS Here are the steps to use Guzzle HTTP Client request in Laravel: Step 1: Install Laravel … Read more

Creating a Chat App with Laravel and Vue [Step-by-Step Guide]

To create a chat application in Laravel with Vue.js, use Pusher’s real-time messaging service, and on the client side, use Laravel Echo and Pusher.js library to update our UI in real-time. Here are the steps to creating an app with Laravel and Vue. Step 1: Install Laravel. laravel new chat # or composer create-project laravel/laravel … Read more

How to Upload Multiple Files in Laravel

To upload multiple files upload in Laravel, use the “jQuery plugin” to populate the field and submit the server; on the backend, we use PHP’s forEach() function to loop through one by one file and upload it. We will use a jQuery plugin to populate the file field and submit one server. Of course, it … Read more

Laravel Stripe Payment Gateway Integration Example

The Stripe payment gateway has built an easy-to-use reputation for developers and store owners. In addition, because of its excellent compatibility with Laravel, Stripe has become the go-to payment gateway for Laravel eCommerce stores. The demand for Saas-based platforms is increasing daily; nowadays, building a subscription-based system is universal. So to make things easy on … Read more

How to Create Filters in Laravel

Here are the steps to create a filter in Laravel. Step 1: Install Laravel. composer create-project laravel/laravel filters –prefer-dist Now, set up the database in your .env file. Step 2: Create migration and dummy data. We are filtering products based on type and categories. So let us create the Product model and migration. So generate via the following command. php … Read more

Laravel Ajax Form Validation Example

To create an Ajax validation in Laravel, use the “default validation with jquery Ajax.” Laravel provides an easy way to use validation without Ajax, but if you want to use Laravel validation with jquery. This is because the server checks all the input fields against defined validation, and if any of the validation fails, it … Read more

How to Export in Excel and CSV in Laravel

To export data in Excel and CSV in Laravel, use the “maatwebsite/excel 3.1″ package. Laravel Excel package is intended at being Laravel-flavoured PhpSpreadsheet: a simple but elegant wrapper around PhpSpreadsheet to simplify the exports and imports. PhpSpreadsheet is a library written in pure PHP and provides a set of classes that allow us to read … Read more

How to Use React.js in Laravel 10 [Step-by-step Guide]

Integrating React.js’s latest version with Laravel 10 is really tough task, and I am writing this step-by-step guide that will help every developer to bootstrap their application. Here are the steps to integrate React into Laravel 10 application: Step 1: Install Laravel 10 composer create-project –prefer-dist laravel/laravel larareact Step 2: Install the correct npm packages … Read more

How to Add Charts in Laravel using Chart.js

Here are the steps to add charts in Laravel: Step 1: Create a Laravel Project composer create-project laravel/laravel LaravelCharts –prefer-dist Go to phpMyAdmin and create one database. Switch to your editor, edit the .env file, and put your database credentials in it. php artisan migrate Step 2: Create one Controller file.  We need to create … Read more

Laravel One to Many Eloquent Relationship Tutorial

A one-to-many relationship in Laravel is “defined as a Single model owning multiple models.” For example, A person has infinite Mobile numbers, or a Blog Post has multiple comments. We can set the one-to-many relationships by defining the function in the model. <?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Get … Read more

Implementation of Datatables in Laravel

To implement datatables in Laravel, you can use the “yajra/laravel-datatables-oracle” package. Laravel Datatables provides a quick search, pagination, ordering, and sorting in the table. The datatables are jQuery plugins that allow you to add advanced interaction controls to your HTML tables data which is very useful in UI/UX. Laravel Datatables also provide Ajax for data … Read more

How to Upload a File in Laravel 10

To upload a file in Laravel 10, use the “Storage::disk(‘local’)->putFileAs( ‘file name’)” function. Laravel Flysystem integration delivers simple drivers for working with local filesystems, SFTP, and Amazon S3. Here is the step-by-step guide to uploading a file in Laravel. Step 1: Install Laravel laravel new fileupload Go inside the folder. Install Laravel UI Package using … Read more

How to Create Laravel with Vue CRUD Application

Here is the step-by-step guide to using Vue with Laravel Step 1: Create a Laravel project Type the following command in your terminal. composer create-project laravel/laravel laravelvuejstutorial –prefer-dist After installing the project, go to the folder and type the following command in your terminal. npm install It will install all the JavaScript dependencies regarding VueJS. … Read more

Laravel Cron Jobs Scheduling To Make Automation Easier

To automate these tasks, a task scheduling system is required. Laravel Cronjob offers an elegant Task Scheduling or Laravel Cronjob Scheduling mechanism. For example, it could be sending promotional emails, optimizing the database, creating backups, or generating site traffic reports. What is Cronjob? Cron is a UNIX-like system task scheduler that runs shell commands at specified … Read more

How to Install and Use Image Intervention in Laravel

Intervention Image has optional support for Laravel and comes with a Service Provider and Facades for easy integration. In addition, laravel includes the vendor/autoload.php file, so you don’t have to require or autoload manually. Also, I have used the intervention/image package to resize the image and then save the image into the database. Step 1: Install Laravel Project … Read more

How to Create Pagination in Laravel [Step-by-step Guide]

To create pagination in Laravel, you can use the “paginate()” method on the query builder or an Eloquent query. The paginate() method sets the proper limit and offsets based on the current page which the user is viewing. Laravel’s paginator is out of the box with the query builder and Eloquent ORM and includes database results. The … Read more

How to Upload Multiple Images in Laravel

To upload multiple images in Laravel, use the “request” facade. You can image upload with validation like images, mimes, max file upload, etc. It can protect the upload script. Here are the steps to upload multiple images in Laravel. Step 1: Configure Laravel. composer create-project laravel/laravel multipleimages –prefer-dist Go to the .env file and add the … Read more

Laravel Dropzone Image Upload Example [Step-by-Step Guide]

Here are the steps to use the Dropzone library to upload an image in Laravel: Step 1: Download Laravel Project Create a Laravel Project by typing the following command. composer create-project –prefer-dist laravel/laravel dropzonefileupload Step 2: Set up a MySQL database Set up the database in the .env file. //.env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dropzonefileupload DB_USERNAME=root DB_PASSWORD= … Read more

Laravel Socialite Login with Facebook Account Example

Here are the steps to log in with Facebook using the laravel socialite package. Step 1: Install a Laravel Create a Laravel project by typing the following command. composer create-project laravel/laravel socialLogin –prefer-dist Go to that project and start the Laravel server by typing the following command. php artisan serve The server starts at URL: … Read more

How to Integrate Firebase into Laravel

To use Laravel with Firebase, use the “kreait/laravel-firebase” package. Step 1: Install Laravel Project composer create-project –prefer-dist laravel/laravel laravelfirebase Step 2: Install laravel-firebase package Open your terminal and enter the following command. composer require kreait/laravel-firebase If, for some reason, you experience an error during installation regarding the platform requirements, you can add the –ignore-platform-reqs flag that will install the … Read more

How to Generate PDF in Laravel with DomPDF

To generate a PDF in the Laravel application, use the “dompdf package.” Dompdf is an HTML-to-PDF converter. The dompdf is (mostly) the CSS 2.1 compliant HTML layout and rendering engine written in PHP. You can generate a pdf file from a view using DomPDF. To export into PDF, We need to write the view file. … Read more

Laravel 8 CRUD Tutorial Step By Step From Scratch

To create a CRUD application in Laravel, your machine should have PHP version >= 7.3 and a composer with additional extensions. BCMath PHP Extension Ctype PHP Extension OpenSSL PHP Extension PDO PHP Extension Tokenizer PHP Extension XML PHP Extension Fileinfo PHP Extension JSON PHP Extension Mbstring PHP Extension Step 1: Installing Laravel If you are … Read more

Dependency Injection and Service Container in Laravel [Step-by-step Guide]

Dependency injection is a method “used to detach hard-coded class dependencies.” The dependencies are inserted at run-time, which allows for greater pliability as dependency execution may be easily reciprocated. Service Container in Laravel is a “Dependency Injection Container and a Registry for the application.” Laravel Container is a powerful tool for managing dependencies and storing … Read more

Laravel Middleware [Step-by-Step Guide]

Laravel Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. Laravel includes a middleware that verifies whether the user of the application is authenticated or not. Here are the steps to create Middleware in Laravel: Step 1: Create a Laravel project composer create-project laravel/laravel LaravelMiddleware –prefer-dist … Read more

How to Use Ajax in Laravel 10

AJAX is the way to communicate between client and server without page refresh. It is the technique of passing data from one server to another without interruption. The syntax of the jQuery Ajax request is the following. jQuery.ajax( url [, settings ] ) Laravel AJAX To use Ajax, you need jQuery, a JavaScript library, to send … Read more