Login Register with Bootstrap Auth in Laravel

Login and Registration with Laravel are very simple, easy, and quick. You can make it within five minutes. Laravel provides you pre-build functionality for login and registration of new users. You just need to follow the following steps.

Step 1: Install Laravel

Create a new Laravel project using composer, if you do have not any project exists. You can use the following command to create a new Laravel project.

composer create-project --prefer-dist laravel/laravel project-name

Step 2: Create database and configurations

Create a new database with any name and configure it in the .env file. You should add database configurations in .env like the following example.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=demo
DB_USERNAME=root
DB_PASSWORD=123456

You need to find and place your database details in the above const .env file.

Step 3: Install Auth package

Now, you need to install the bootstrap UI and auth package using composer. Run the following command step by step.

composer require laravel/ui

php artisan ui bootstrap --auth

npm install && npm run dev

Note: In case you got the npm command not found error then install npm first and then run the above command. For windows, you can install the node LTS package. So, that you can able to run the npm commands.

Step 4: Run Migrations

After the above, you need to run the migration to create a table for the user. You can use the following command to do this.

php artisan migrate

Step 5: Set Routes

After successfully installing the above packages, you need to set routes for auth functionality. So, you just need to set one route for managing auth basic process. Define the routes for login and registration in web.php

Auth::routes();

Note: If the above route is already set just leave this step. You can customize the views for login and registration by editing the files in the resources/views/auth folder.

Step 6: Run the Project

Now, you serve your project by following the command and are able to see the auth functionality in your project.

php artisan serve

Note: In case you got any CSS issues in your login register route then just need to stop the serve command and re-run the following command.

npm install && npm run dev

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

 

How to create Middleware in Laravel

Middleware is a mechanism that allows you to filter HTTP requests entering your application. It sits between your application and the user’s browser, intercepting incoming requests and performing actions before passing the request on to the application’s routes or controllers. Middleware is useful for tasks such as authentication, logging, and input validation.

Laravel provides several middlewares out of the box, such as the auth middleware for authentication, the csrf middleware for protecting against cross-site request forgery attacks, and the throttle middleware for rate limiting.

To use a middleware, you can either apply it to individual routes in your routes/web.php file, or apply it globally to all routes by adding it to the $middleware array in your app/Http/Kernel.php file.

Step 1: Open the Terminal

Open your terminal or command line and navigate to your Laravel project directory.

Step 2: Create a middleware file

Use the make:middleware Artisan command to generate a new middleware class. For example, to create a middleware called CheckAgeMiddleware, run the following command.

php artisan make:middleware CheckAgeMiddleware

This will create a new file called CheckAgeMiddleware.php in the app/Http/Middleware directory.

Step 3: Modify a middleware file

Open the CheckAgeMiddleware.php file and modify the handle method to add your middleware logic. This method takes two parameters: $request and $next. The $request parameter contains the HTTP request object, while the $next parameter is a closure that represents the next middleware in the chain. You can modify the request object, or return a response object to stop the middleware chain.

Here’s an example of a CheckAgeMiddleware that checks if the user is over 18 years old.

namespace App\Http\Middleware;
use Closure;

class CheckAgeMiddleware
{
    public function handle($request, Closure $next)
    {
        $age = $request->input('age');

        if ($age < 18) {
            return response('You must be over 18 to access this page.', 403);
        }

        return $next($request);
    }
}

Step 4: Register Middleware

Register your middleware in the app/Http/Kernel.php file. This file contains an array of middleware groups, each with its own set of middleware classes. You can add your middleware to an existing group, or create a new group.

To add your middleware to an existing group, find the group in the $middlewareGroups property, and add your middleware class to the array.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        // Add your middleware here
        \App\Http\Middleware\CheckAgeMiddleware::class,
    ],

    // ...
];

To create a new middleware group, add a new key-value pair to the $middlewareGroups array.

protected $middlewareGroups = [
    'web' => [
        // ...
    ],

    'api' => [
        'throttle:60,1',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        // Add your middleware here
        \App\Http\Middleware\CheckApiKeyMiddleware::class,
    ],
];

Step 5: Add Middleware in Route

Use your middleware in a route or controller. To use your middleware in a route, you can add it to the route definition.

Route::get('/dashboard', function () {
    // ...
})->middleware('checkage');

To use your middleware in a controller, you can add it to the constructor or to a specific method.

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('checkage');
    }

    public function index()
    {
        // ...
    }
}

You can set middleware in route either in the controller.

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

Routing in Laravel

In Laravel, you can define routes using the Route facade, which provides a simple and expressive way to define HTTP routes. Following are some examples of routes how to create routes in Laravel.

Route is a URL pattern that maps to a specific controller action or function in your application. Laravel provides a powerful routing system that allows you to define routes for different HTTP methods like GET, POST, PUT, DELETE, etc.

Laravel has two types of route files one is web.php and the second is api.php. web.php defined the web or HTTP route and api.php defined the API calling route. In the API route automatically add api prefix in the URL. api prefix will add after base URL.

Step 1: Basic Route

The most basic route definition in Laravel looks like this.

Route::get('/', function () {
    return view('welcome');
});

This creates a route that responds to HTTP GET requests to the root URL (/) and returns the welcome view.

Step 2: Route with Parameters

You can define routes that accept parameters by enclosing the parameter name in curly braces {}.

Route::get('/users/{id}', function ($id) {
    return "User ID: " . $id;
});

This creates a route that accepts a parameter called id and returns a string with the value of the parameter.

Step 3: Route with Optional Parameters

You can make a route parameter optional by enclosing it in curly braces with a question mark ?.

Route::get('/products/{id?}', function ($id = null) {
    if ($id) {
        return "Product ID: " . $id;
    } else {
        return "All Products";
    }
});

This creates a route that accepts an optional parameter called id, and if provided, returns the product ID. If the parameter is not provided, it returns a message indicating all products.

Step 4: Named Route

You can give a name to a route by chaining the name method to the route definition.

Route::get('/contact', function () {
    return view('contact');
})->name('contact');

This creates a route that responds to HTTP GET requests to /contact and gives it a name contact. You can use the name later in your application to generate URLs or redirects.

Step 5: Route Group

You can group multiple routes that share the same middleware or prefix.

Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', function () {
        return view('dashboard');
    });
    Route::get('/profile', function () {
        return view('profile');
    });
});

This creates a group of routes that use the auth middleware, which means that the user must be authenticated to access them.

You can also define a route that maps to a controller method instead of a closure function. Here is an example of defining a route that maps to a UserController method.

Route::get('/users', 'UserController@index');

In the example above, we define a route that responds to the /users URL and maps to the index method of the UserController.

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to send email with HTML template using gmail SMTP in Laravel 8

In this post, I will let you know how to send email in laravel using Gmail SMTP in simple and easy steps. Laravel 8 provides several ways to send an email and you can use any email service provider. First of all, you need to install laravel and after that need to follow the following steps.

Step 1: .env Configuration

Set up the SMTP configuration in your .env file and you can find out the .env file in the root directory of the project. You can use your Gmail login email and password in MAIL_USERNAME, MAIL_PASSWORD but if you want to prevent your email password from attackers then you should use App Password. As I suggest you must use the App Password in place of the Gmail login password.

You can generate App Password from your Gmail account using a few steps. Here is a reference link: https://support.google.com/mail/answer/185833?hl=en

Note: In case, you are not able to see the .env file in the root directory of your project then you should show the hidden file because the .env file is a hidden file. If you are only able to see .env.example then need to create a .env file first.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME={YOUR SMTP EMAIL ADDRESS}
MAIL_PASSWORD={YOUR SMTP EMAIL PASSWORD}
MAIL_ENCRYPTION=tls

Step 2: Create a Controller

Now, you need to create a controller with any name or if you want to use any existing controller then you can use it.
I am creating here controller named as UserController with the help of the following command.

php artisan make:controller UserController

Once your controller is created you are able to see some default codebase you can replace and modify by using the following code.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class UserController extends Controller
{
    public function testSendMail()
    {
        $data = array('name' => "User");

        Mail::send('mail', $data, function($message) {
            $message->to('toemail@example.com', 'Welcome Mail')
                    ->subject('Laravel HTML Testing Mail');
            $message->from('fromemail@example.com', 'Programming With Ajay');
        });

        dd('Mail Send Successfully');
    }
}

Step 3: Create a Route

After creating the controller you need to set a route for it. You need to add the following code to the web.php file. You can find the web.php file in the routes directory.

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/


Route::get('/sendemail', [App\Http\Controllers\UserController::class, 'testSendMail']);

Step 4: Create a Blade file

Now, you need to create a blade file for the email template and the name should be mail.blade.php . Because we had set the mail name in the controller. You can change it as per your requirements.

<html>
<body>
<h1>Hi, {{ $name }}</h1>
<p>Sending dynamic data Mail from Laravel.</p>
</body>
</html>

After this, you need to run the following URL, and the server URL may be different in your case. So, you must run your server base URL with the route name sendemail .

http://127.0.0.1:8000/sendemail

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to install Laravel 7, 8, 9 by composer

Server Requirement:

The Laravel framework has a few system requirements. If you are installing laravel 7. If you are trying to install Laravel by composer then it will automatically pick the laravel version according to your PHP version. But you can specify the version while installing it using composer.

  • PHP >= 7.2.5
  • BCMath PHP Extension
  • Ctype PHP Extension
  • Fileinfo PHP extension
  • JSON PHP Extension
  • Mbstring PHP Extension
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Step 1:

Visit the following URL and download composer to install it on your system.
https://getcomposer.org/download/

Note: In case, the composer already installed your system then you don’t need to run the first step.

To verify composer is installed or not, by running  composer the command in terminal/cmd

Step 2:

You can install a specific version using the following command. Just need to change the version in place of 7.0

composer create-project --prefer-dist laravel/laravel:^7.0 blog

Install laravel according to the installed PHP version in your system by the following command.

composer create-project --prefer-dist laravel/laravel blog

It will take few minutes according to your internet speed.

Note: the blog is your folder/directory name, So you can change it as per your choice.

Output:

Step 3:

First, you need to go blog directory by the following command.

cd blog

Start the Laravel service by executing the following command. This command will start a development server at http://localhost:8000

php artisan serve

Output:

Copy the URL from the terminal http://127.0.0.1:8000 in the above screenshot and open that URL in the browser. If you see the following screen, it implies Laravel has been installed successfully.

Note: 
The above screenshot URL might be different in your case so use them. Also, the Web screen may be different for you due to the different versions of Laravel.

Output:

 

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to send ajax request from WordPress using POST method

Ajax is a way to get, post, update, and delete data without refreshing the page. WordPress ajax is different as compared to the normal ajax in PHP. The WordPress ajax, URL is the same for all ajax requests but there is one param action and it is unique for every request. Also, the action param can define which function call on an ajax request.

Step 1: template file

Following code for the template file code. In this code, we have created a form with name and age fields and we will post this form data using ajax. Also, after posting data we will get data posted in ajax response and print it on the same page. Using form ID sendAjaxFormId we will post this form and after the ajax response display data using IDs responseName responseAge .

<form id="sendAjaxFormId">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name">
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" id="age" placeholder="Enter age">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<p>Entered Name: <span id="responseName"></span></p>
<p>Entered Age: <span id="responseAge"></span></p>

Step 2: custom.js file

In the custom.js file, we have JQuery code to send Ajax request to the function.php file and return back the response in the same file. Some information about Ajax params:

formData => used to send/post data.

url => to set Ajax request URL (it’s common for all ajax requests).

type => Ajax request method (it can get, post, delete, etc)

dataType => Ajax request and response data type.

data => data param contains action, posted data two params. Action should be unique for every request.

success => if the request is successfully processed, then get a response in success function/param.

error => if the request does not process successfully or occurred error during this then the error can catch in the error function.

jQuery(document).ready(function() {
    jQuery('#sendAjaxFormId').submit(function(ev) {
        ev.preventDefault();
        var formData = {
            name: jQuery('#name').val(),
            age: jQuery('#age').val()
        }
        
        jQuery.ajax({
            url: ajaxObject.ajaxUrl,
            type: "post",
            dataType: "json",
            data: {
                action: 'form_post_data',
                data: formData
            },
            success: function(response) {
                console.log(response);
                jQuery('#responseName').html(response.data.name);
                jQuery('#responseAge').html(response.data.age);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });    
});

Step 3: function.php

In this file, we have done two things. First, handle ajax request and second localize PHP variables to pass in JS file.

wp_enqueue_scripts hook is used to enqueue the JS file. wp_localize_script is used to pass params to custom.js file. So, we passed the Ajax URL in the following code.

wp_ajax_form_post_data is a combined hook. wp_ajax_ is common for all requests and form_post_data is an action that is passed from the custom.js file. wp_ajax_nopriv_ hook allows running requests by unauthenticated or any user. So, you can miss or remove this from your code.

In the handleFormPostData method, we checked and return the same posted data in JSON format. Because we set dataType JSON while sending Ajax from the JS file.

add_action('wp_enqueue_scripts', 'myScriptEnqueue');

function myScriptEnqueue() {
    wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
    wp_localize_script(
        'custom-js',
        'ajaxObject',
        array('ajaxUrl' => admin_url('admin-ajax.php'))
    );
}

add_action('wp_ajax_form_post_data', 'handleFormPostData');
add_action('wp_ajax_nopriv_form_post_data', 'handleFormPostData');

function handleFormPostData() {
    $response = array();
    $response['message'] = "Error";
    $response['data'] = [];

    if (isset($_POST['data']) && !empty($_POST['data'])) { 
        $response['message'] = "Success";       
        $response['data'] = $_POST['data'];
    }
        
    echo json_encode($response);
    wp_die();
}

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to install WordPress

WordPress is an easy job to install and run. It takes just 5 minutes to install and run the basic setup of your website. WordPress gives you lots of prebuild features like you can set any pre-build theme, or plugin as per your requirements. Also, there are some ways to customize WordPress as well.

WordPress recommends itself to run PHP 7.4 at least. PHP 7.4 supported WordPress version 5.3 to 6.1 (latest). You can check the supported version list on the official documentation of WordPress.  PHP Compatibility and WordPress Versions

The following steps are for localhost in case you are installing it on the server then use server name in place of localhost to manually install WordPress.

Step 1:

Download WordPress from its official website Download WordPress, if you have not already downloaded it. Extract the zip file and place it PHP code run directory. In the htdocs directory (Folder), if you are using xampp in windows. In Linux OS you may find the html directory.

Note: You can rename the extracted file whatever you want. I renamed it with wordpress-6.1.1

Step 2:

Go to PhpMyAdmin and add the new database for your website. I created the same name database as the directory name of unzip files wordpress-6.1.1 . After that hit the URL http://localhost/wordpress-6.1.1/ and you will see the install screen in the browser window.

Note: Above install URL may be different in your case. So, use http://localhost/{YOUR DIRECTORY NAME}/ it to run the installation.

Step 3:

Now, You will see different languages, you can select any language whatever you want to install for the website. English is a global language and most people know about English in the World. So, I am selecting English and clicked on the continue button.

Step 4:

Now, you will the welcome screen with some information. You just need to click on Lets Go the button.

Note: If for any reason this automatic file creation does not work, do not worry. All this does is fill in the database information to a configuration file. You may also simply open wp-config-sample.php in a text editor, fill in your information, and save it as wp-config.php.

Step 5:

Add your database connection details. You can choose a different prefix name, i.e. dbt_ or may proceed with the default prefix name wp_

After filling in the database details click on submit button. You will see the following screen. Click on the Run the installation button.

Step 6:

After this, you will see the information needed screen you just add some information for the site i.e. site name, admin login details, email, etc., and click on the Install WordPress button.

Note: Search engine visibility options for SEO purposes. So, if you are on localhost then check it because nobody wants to index our local system sites. But if you are installing it on the server then leave it unchecked.

Step 7:

After this, you will see the success screen, click on the login button and you will see the wp-admin login page. Just log in with the details that you added in step 6 and you will see the admin dashboard, where you can manage all the things.

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.