Friday, 2 October 2020

Commonly Used Laravel Artisan Console Commands

Laravel, the widely acclaimed PHP framework, enhances web development with its elegant syntax and comprehensive features. Among its powerful tools, the Artisan Console stands out, offering developers a suite of command-line operations to streamline project tasks. This brief article explores the commonly used Laravel Artisan Console commands, essential for efficient development workflows.

Most of the time, Laravel developers use a lot of different Laravel Artisan commands to clear caches
to run the development server, creating controllers, models, and other useful artisan options.
    Key Laravel Artisan Commands

  1. php artisan cache:clear  

    This command clears the application cache. It is especially useful when your application is serving outdated data or when you have made changes that are not reflecting properly. Clearing the cache ensures that fresh data is loaded and improves overall performance.

  2. php artisan config:cache 

    Laravel caches configuration files for better performance. If you update any configuration settings and they are not taking effect, this command clears the configuration cache so that the latest settings are applied.

  3. php artisan route:clear  Clear Application route cache

    When routes are cached for performance optimization, sometimes new routes may not be recognized. Running this command clears the route cache and allows Laravel to reload updated route definitions.

  4. php artisan view:clear  
Laravel compiles Blade templates into cached files. If your view changes are not visible, this
The command clears the compiled view files and ensures updated templates are rendered.

      5. php artisan serve  


This command starts a local development server, usually accessible at http://127.0.0.1:8000.
        It is extremely helpful for testing and developing your Laravel application without needing
additional server configuration.

6. php artisan serve:
Launch a development server, making your application accessible at a localhost URL. This command is particularly useful for quick testing and development.

7. php artisan make:migration create_table_name_table: Generate a new migration file for creating a database table. Migrations ensure database structure.
consistency across different environments.

8. php artisan db:seed:
Database seeding allows you to populate tables with dummy or default data. This is very useful for testing and development purposes, especially when working with large applications.
.
9. php artisan tinker: Enter a REPL (Read-Eval-Print Loop) environment that allows you to interact with your Laravel. application in a command-line interface, facilitating debugging and experimentation.

  1. Conclusion The Laravel Artisan Console is an essential tool for every Laravel developer. It simplifies complex development tasks, increases productivity, and ensures smooth workflow management. From clearing caches and running local servers to managing migrations and seeding databases, Artisan commands play a critical role in modern Laravel development. If you want to become a professional Laravel developer, mastering Artisan commands is a must. By using these powerful command-line tools effectively, you can build faster, cleaner, and more scalable web applications with confidence.

Thursday, 1 October 2020

Laravel 6 and 7 Authentication

Authentication is one of the most important features of any modern web application. Whether you are building a simple website or a complex system, user login, registration, and password management are essential components. Fortunately, the Laravel framework provides built-in tools that make implementing authentication simple and efficient.

In earlier versions of Laravel, developers could easily generate authentication scaffolding using the make:auth command. However, starting from Laravel 6, this command was removed from the core framework. Instead, authentication scaffolding was moved into a separate package called Laravel UI. This change allows developers to install only the features they need while keeping the framework lightweight.

In this article, we will explain how authentication works in Laravel 6 and Laravel 7, how to install the Laravel UI package, and how to generate authentication scaffolding for your application.

Understanding Authentication in Laravel 6 and 7.

Authentication refers to the process of verifying a user’s identity before granting access to certain parts of an application. It usually includes features such as login, registration, password reset, and user sessions.

Before Laravel 6, developers could simply run the make:auth command to generate all authentication files automatically. This command created controllers, routes, and views needed for login and registration.

However, with the release of Laravel 6, the authentication scaffolding was moved into a separate package called Laravel UI. This package provides the same authentication features but keeps them outside the core framework.

Laravel 7 continued using the same system and improved developer experience by refining the tools and documentation. As a result, developers can still quickly implement authentication by installing Laravel UI and generating the necessary files.

Why Laravel? Removed the make:auth command.

Many developers noticed that the make:auth command no longer exists in Laravel 6 and later versions. This change was made to make the framework more modular and flexible.

Instead of including authentication scaffolding by default, Laravel now allows developers to install it only when needed. This helps keep the base installation lightweight and reduces unnecessary dependencies.

The new approach also gives developers more flexibility to choose different front-end stacks, such as Bootstrap, Vue.js, or React, when generating authentication views.

Because of these improvements, Laravel UI became the recommended way to add authentication scaffolding in Laravel 6 and Laravel 7 applications.

Installing Laravel UI in Laravel 6.

To enable authentication features in a Laravel 6 application, you must install the Laravel UI package first. This package provides the commands needed to generate authentication controllers and views.

You can install Laravel UI using Composer by running the following command in your project directory:

composer require laravel/ui

After installing the package, several new Artisan commands will become available. These commands help you generate authentication scaffolding quickly.

To view all available UI commands, run the following command:

php artisan ui --help

This command will display a list of options that allow you to generate authentication interfaces using different front-end frameworks.

Generating Authentication Scaffolding.

Once Laravel UI is installed, you can generate the authentication system using an Artisan command.

Run the following command to generate authentication scaffolding:

php artisan ui:auth

This command automatically creates the required authentication structure for your Laravel application.

The following components will be generated:

HomeController

Authentication routes

Authentication views

Layout files

These files provide a complete authentication system, including login, registration, and password reset functionality.

Files Generated by the ui:auth Command.

When you run the authentication scaffolding command, Laravel automatically generates several important files.

1. HomeController

The HomeController is responsible for handling requests after a user logs in. It usually directs the authenticated user to the dashboard or home page.

2. Authentication Routes

Laravel automatically registers routes required for authentication. These routes handle login, logout, registration, and password reset processes.

3. Authentication Views

Several Blade templates are generated inside the resources/views/auth directory. These include:

Login page

Registration page

Forgot password page

Reset password page

These views provide the user interface for authentication.

4. Layout File

The command also generates an app.blade.php layout file, which serves as the main layout template for authentication pages.

Generating Only Authentication Views.

In some cases, you may already have controllers and routes configured in your application. In such situations, you might only want to generate authentication views.

Laravel allows you to generate only the view files by using the --views option.

Run the following command:

php artisan ui:auth --views

This command will generate only the authentication views without modifying controllers or routes.

This is especially useful when you want to customize authentication layouts while keeping your existing backend logic unchanged.

Advantages of Using Laravel UI Authentication.

Using Laravel UI provides several advantages for developers building applications with Laravel 6 or Laravel 7.

First, it simplifies authentication implementation by automatically generating all necessary files. This saves development time and reduces the chances of errors.

Second, the package offers flexibility. Developers can easily integrate different front-end technologies like Bootstrap, Vue, or React while generating authentication interfaces.

Third, Laravel UI follows Laravel’s best practices and coding standards. This ensures that the generated authentication system is secure, organized, and easy to maintain.

Finally, it helps beginners quickly implement authentication without needing deep knowledge of authentication logic.

Conclusion.

Authentication is an essential feature of most web applications, and Laravel makes it incredibly easy to implement. While earlier versions of Laravel used the make:auth command, Laravel 6 and Laravel 7 introduced a new approach using the Laravel UI package.

By installing the laravel/ui package, developers can quickly generate authentication scaffolding, including controllers, routes, and views. The process requires only a few simple commands and provides a complete authentication system.

Laravel UI also offers flexibility, allowing developers to generate only the components they need, such as authentication views. This modular approach keeps Laravel lightweight while still providing powerful authentication features.

Saturday, 7 March 2020

PostTooLargeException in ValidatePostSize.php in laravel

PostTooLargeException in Laravel



Uploading files such as images, PDFs, or documents is a common feature in web applications built with the Laravel framework. However, developers sometimes encounter the Illuminate\Http\Exceptions\PostTooLargeException error while uploading large files. This issue usually appears when the file size exceeds the limits defined in the server’s PHP configuration.

By default, PHP allows only small file uploads, typically around 2MB. When a user tries to upload a file larger than the allowed size, Laravel throws the PostTooLargeException error to prevent the request from being processed. Understanding the root cause of this issue helps developers quickly resolve it and ensure smooth file uploads in their applications.

In this article, we will explain what the PostTooLargeException error means, why it occurs, and the best methods to fix it in Laravel projects.

Understanding the Error

The PostTooLargeException occurs when a form submission contains data that exceeds the maximum size allowed by the server configuration. Laravel detects that the incoming request is larger than the permitted limit and immediately throws an exception.

This error is commonly seen when uploading large images, videos, or document files. Since file uploads are transmitted through HTTP POST requests, the server must allow a sufficient size limit to handle these requests.

Another important factor is that Laravel itself does not impose strict upload limits by default. Instead, it follows the configuration settings defined in PHP and the web server environment.

When the size of the request exceeds the configured limits, the request fails before Laravel can even process the uploaded file. That is why developers often see the error page Illuminate/Http/Exceptions/PostTooLargeException. html.

Common Causes

The PostTooLargeException error can occur due to several configuration limitations. Below are some of the most common reasons why this issue appears.

1. Default PHP Upload Limit

One of the primary reasons for this error is the default PHP upload size restriction. In many servers, the upload_max_filesize value is set to 2MB. If a user attempts to upload a file larger than this limit, the request will fail.

2. Small POST Request Size

Another important PHP configuration is post_max_size. This setting controls the total size of the entire POST request, including file uploads and form data. If the file size exceeds this value, the server will reject the request.

3. Web Server Configuration Limits

Sometimes the issue is not related to PHP but to the web server configuration. For example, Apache HTTP Server or NGINX may impose additional restrictions on request sizes, which can trigger the PostTooLargeException error.

How to Fix the Error

Fortunately, fixing the PostTooLargeException error in Laravel is relatively simple. You just need to update a few configuration settings on your server.

1. Increase PHP Post Max Size

The first step is to increase the maximum POST request size in your php.ini configuration file.

Open the php.ini file and update the following values:

post_max_size = 64M

upload_max_filesize = 64M

These settings allow users to upload files up to 64 MB. You can increase or decrease the size according to your project requirements.

After modifying the file, make sure to restart your web server so that the new settings take effect.

2. Update upload_max_filesize

The upload_max_filesize directive defines the maximum size allowed for a single uploaded file. If this value is smaller than the file being uploaded, the request will fail.

Make sure this value is large enough for your application. For example:

upload_max_filesize = 64M

This ensures that Laravel can handle larger file uploads without throwing exceptions.

3. Check Web Server Limits

If you are using NGINX, you may also need to increase the client_max_body_size directive in the server configuration.

Example configuration:

client_max_body_size 64 M;

For Apache HTTP Server, you may need to update settings in the .htaccess file.

Example:

php_value upload_max_filesize 64M

php_value post_max_size 64M

After making these changes, restart the server to apply the updated configuration.

4. Adjust Laravel Environment Settings

Although Laravel mainly relies on PHP configuration, sometimes updating the .env file can help maintain consistency in your application settings.

You can define file upload limits or validation rules within your Laravel controller or request validation logic to ensure users upload files within acceptable limits.

For example, you can validate file uploads using Laravel validation rules:

'file' => 'required|file|max:65536'

This ensures that uploaded files stay within the allowed size range.

Conclusion

The PostTooLargeException error in Laravel is a common issue that occurs when users attempt to upload files larger than the server’s configured limits. Since Laravel depends on PHP settings, incorrect configuration values can easily trigger this exception.

Fortunately, the solution is straightforward. By increasing the post_max_size and upload_max_filesize values in the php.ini file, developers can allow larger file uploads in their applications.

In addition, checking web server configurations such as NGINX or Apache HTTP Server ensures that request size limits do not interfere with file uploads.

By properly configuring PHP and server settings, developers can prevent the PostTooLargeException error and provide a smooth file upload experience for users.

Wednesday, 16 January 2019

Send Emails Using Gmail SMTP in Laravel

Sending emails is an essential feature in most web applications. Whether it is user registration, password reset, notifications, or order confirmations, email functionality plays a critical role. Laravel provides a powerful and simple mailing system that allows developers to send emails using different mail drivers.

One of the most common ways to send emails in Laravel is by using Gmail SMTP. Gmail’s SMTP server is reliable, secure, and easy to configure. By integrating Gmail SMTP with your Laravel application, you can quickly enable email functionality without setting up a complex mail server.

In this article, we will explain how to configure Gmail SMTP in Laravel step-by-step and send emails from your application.

Thursday, 27 September 2018

Laravel Eloquent ORM get last insert id

In modern web development, working with databases is a common job. When developers use the Laravel framework to make apps, they often need to add new records to a database and then get the ID of the record they just added right away. Fortunately, Laravel's Eloquent ORM makes this quick and easy.

When you use Eloquent to add a new record in Laravel, the model instance is automatically updated with the primary key that the database created and that increases by one. This means you can get the last inserted ID right from the model without having to run any more queries.

This guide will show you how to get the last inserted ID in Laravel, why it's useful, and other ways to do it with the query builder.

How to Understand the Last Insert ID in Laravel

When you add a new record to a database table with an auto-incrementing primary key, the database makes a unique ID for that record on its own. After the record is saved, Laravel's Eloquent ORM automatically gets this value and gives it to the model instance.

This built-in feature helps developers avoid having to write extra SQL queries to get the last record that was added. The ID is available right away after the save() method is called, though.

Another advantage of this feature is better performance. Laravel takes care of getting the inserted ID for you, which cuts down on unnecessary database calls and keeps the code clean and easy to read.

Laravel's design philosophy includes this behavior, which makes complicated database tasks easy and friendly for developers.

Common Situations Where Last Insert ID Is Used

Retrieving the last inserted ID is very useful in many real-world web development scenarios. Developers frequently rely on it to create relationships between different database tables.

1. Creating Related Records

When adding data to related tables, the last inserted ID is often needed as a foreign key. For instance, you might need the user ID to save profile or address information after making a user record.

2. Sending Users to a Different Resource

After submitting, many apps send users to the new record page. The ID you put in helps make the right URL.

3. Activity Logging

Some systems log user activities or transactions immediately after a record is created. The last inserted ID helps reference the correct entry.

4. Order and Transaction Systems

In e-commerce applications, once an order is created, the order ID is used to insert order items, payment records, and shipping details.

How to Get the Last Insert ID Using Laravel Eloquent

Using the Eloquent model instance is the easiest and most common way to get the last inserted ID.

When you make a new model and save it, Laravel automatically gives the model's id property the ID that was made.

For instance,

$user = new User;

$user->name = "Tom";

$user->phone = "+154483480";

$user->save();

$last_insert_id = $user->id;

Explanation

A new User model instance is created.

The name and phone attributes are assigned values.

The save() method inserts the record into the database.

Laravel automatically sets the generated ID in $user->id.

After the save() method executes, you can directly access the ID from the model object.

This is the recommended approach because it follows Laravel’s ORM pattern and keeps your code simple and readable.

Alternative Method: Using the Query Builder

Laravel also provides a query builder that allows developers to interact with the database without using models.

If you are not using Eloquent models, you can retrieve the last inserted ID using the insertGetId() method.

Example

$last_id = DB::table('products') ->insertGetId([

    'name' => 'Laptop',

    'price' => 1200

]);

How It Works


The insertGetId() method inserts a new record into the specified table.


After inserting the record, Laravel automatically returns the generated primary key.

The returned ID is stored in the $last_id variable.

This method is particularly useful when working with raw database queries or when you prefer not to create an Eloquent model.

Best Practices for Retrieving Inserted IDs

While Laravel makes retrieving inserted IDs easy, following best practices ensures your code remains efficient and maintainable.

Use Eloquent whenever you can.

Eloquent helps you keep your code neat and easy to work with, especially on big projects.

Make sure that your table has a primary key that automatically increases.

Unless you set it up differently, Laravel expects the primary key to automatically increase.

Don't make database queries that aren't needed.

There is no need to run more SQL queries because Laravel already gives the inserted ID through the model instance.

For complicated tasks, use database transactions.

Transactions help keep data consistent when you are adding data to more than one related table.

Conclusion

When working with databases, Laravel makes it easy and clean to get the last inserted ID. The Eloquent ORM makes it easy for developers to get the primary key that was created right from the model instance after saving a record.

This feature makes it easier to do things like make related records, log activities, and send users to new resources. Laravel takes care of everything behind the scenes, so you don't have to write complicated SQL queries.

If you don't want to use Eloquent, Laravel's Query Builder has the handy insertGetId() method that does the same thing.

Developers can write cleaner, more efficient Laravel apps that still perform well and can handle more users by learning these methods and using them correctly.

.htaccess not working even though allowoverride is enabled

You're not the only one who has had the annoying problem with Apache where your file doesn't work even after you enable it. You'...