Laravel 8 Sanctum API Authentication Tutorial

Laravel 8 Sanctum API Authentication Tutorial

Hi Dev,

In this blog,I will learn you how to use sanctum api authenticationin laravel 8. We will Show example of sanctum api authentication in laravel 8. it's simple example of laravel 8 sanctum example. you'll learn laravel 8 sanctum rest api example. So, let's follow few step to create example of laravel 8 sanctum api token tutorial.

Laravel 8 Sanctum provides a simple authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum also allows each user of your application to generate multiple API tokens for their account.

You also want to create api for your mobile application than you can follow this tutorial for how to create rest api step by step with laravel 8 and sanctum. If you are new than don't worry about that i written tutorial step by step.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 1: Install Laravel 8

In this step we need to install sanctum via the Composer package manager, so one your terminal and fire bellow command.

composer require laravel/sanctum

After successfully install package, we need to publish configuration file with following command:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

we require to get default migration for create new sanctum tables in our database. so let's run bellow command.

php artisan migrate

Next, we need to add middleware for sanctum api, so let's add as like bellow:

app/Http/Kernel.php
....
'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
....
Step 3: Sanctum Configuration

In this step, we have to configuration on three place model, service provider and auth config file. So you have to just following change on that file.

In model we added HasApiTokens class of Sanctum,

In auth.php, we added api auth configuration.

app/Models/User.php
<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens;
  
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
  
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Step 4: Add Food Table and Model

In this step, We require to create migration for posts table using Laravel 8 php artisan command, so first fire bellow command.

php artisan make:migration create_foods_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create Foods table.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFoodsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('foods', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('foods');
    }
}

After create migration we need to run above migration by following command:

php artisan migrate

After create "foods" table you should create Food model for foods, so first create file in this path app/Models/Food.php and put bellow content in item.php file.

app/Models/Food.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Food extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'detail'
    ];
}
Step 5: Create API Routes
<?php
  
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\FoodController;
  
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
  
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
     
Route::middleware('auth:sanctum')->group( function () {
    Route::resource('foods', FoodController::class);
});
Step 6: Create Controller Files

In this step, we have create new controller as BaseController, FoodController and RegisterController, i created new folder "API" in Controllers folder because we will make alone APIs controller, So let's create both controller.

app/Http/Controllers/API/BaseController.php
<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class BaseController extends Controller
{
    /**
    * success response method.
    *
    * @return \Illuminate\Http\Response
    */
    public function sendResponse($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];


        return response()->json($response, 200);
    }

    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];


        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }

        return response()->json($response, $code);
    }
}
app/Http/Controllers/API/RegisterController.php
<?php

namespace App\Http\Controllers\API;
use App\Http\Controllers\API\BaseController as BaseController;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;

class RegisterController extends BaseController
{
     /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->plainTextToken;
        $success['name'] =  $user->name;
   
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}
app/Http/Controllers/API/FoodController.php
<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\Food;
use Validator;
use App\Http\Resources\Food as FoodResource;

class FoodController extends BaseController
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $foods = Food::all();
    
        return $this->sendResponse(FoodResource::collection($foods), 'Foods retrieved successfully.');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $food = Food::create($input);
   
        return $this->sendResponse(new FoodResource($food), 'Food created successfully.');
    } 
   
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $food = Food::find($id);
  
        if (is_null($food)) {
            return $this->sendError('Food not found.');
        }
   
        return $this->sendResponse(new FoodResource($food), 'Food retrieved successfully.');
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Food $food)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'name' => 'required',
            'detail' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $food->name = $input['name'];
        $food->detail = $input['detail'];
        $food->save();
   
        return $this->sendResponse(new FoodResource($food), 'Food updated successfully.');
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Food $food)
    {
        $food->delete();
   
        return $this->sendResponse([], 'Food deleted successfully.');
    }
}
Step 7: Create Eloquent API Resources

Now In this step,This is a very important step of creating rest api in laravel 8. you can use eloquent api resources with api. it will helps you to make same response layout of your model object. we used in FoodController file. now we have to create it using following command.

php artisan make:resource Food

Now there created new file with new folder on following path:

app/Http/Resources/Food.php
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Food extends JsonResource
{
     /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'detail' => $this->detail,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->format('d/m/Y'),
        ];
    }
}

Now we are ready to to run full restful api and also passport api in laravel. so let's run our example so run bellow command for quick run:

php artisan serve

make sure in details api we will use following headers as listed bellow:

'headers' => [

    'Accept' => 'application/json',

    'Authorization' => 'Bearer '.$accessToken,
]
Now simply you can run above listed url like as bellow screen shot: 1) Register API: Verb:GET, URL:http://localhost:8000/api/register
Laravel 8 Sanctum API Authentication Tutorial
2) Login API: Verb:GET, URL:http://localhost:8000/api/login
Laravel 8 Sanctum API Authentication Tutorial
3) Food List API: Verb:GET, URL:http://localhost:8000/api/foods
Laravel 8 Sanctum API Authentication Tutorial
4) Food Create API: Verb:POST, URL:http://localhost:8000/api/foods
Laravel 8 Sanctum API Authentication Tutorial
5) Food Show API: Verb:GET, URL:http://localhost:8000/api/foods/{id}
Laravel 8 Sanctum API Authentication Tutorial
6) Food Update API: Verb:PUT, URL:http://localhost:8000/api/foods/{id}
Laravel 8 Sanctum API Authentication Tutorial
7) Food Delete API: Verb:DELETE, URL:http://localhost:8000/api/food/{id}
Laravel 8 Sanctum API Authentication Tutorial
It wiil help you....

Laravel Create Custom Log File Example

Laravel Create Custom Log File Example

Hi Guys,

Today,I will learn you how to create custom log file in laravel? This article will give you simple example of laravel custom log file example. it's simple example of create custom log file in laravel. Follow bellow tutorial step of how to make custom log file laravel.

Laravel by default provide storage/logs/laravel.log file location where it will display log file. but sometime you may require to create log file with specific task. for example, if you are working with payment task and you need all logs separately log file for payment, so you can easily find out solution.

Here, i will give you very simple example, so let's see how to add custom channel with new log file location.

config/logging.php
...
'channels' => [
        ...
        'itwebtuts' => [
            'driver' => 'single',
            'path' => storage_path('logs/itwebtuts.log'),
            'level' => 'info',
        ],
....
Route Code:
Route::get('create-custom-log', function () {
    \Log::channel('itwebtuts')->info('This is testing for itwebtuts.com!');
    dd('done');
});
now you can check your own. storage/logs/itwebtuts.log
[2021-04-13 11:46:41] local.INFO: This is testing for itwebtuts.com!  
It will help you....

Laravel 8 Pluck Example Tutorial

Laravel 8 Pluck Example Tutorial

Hi Guys,

Today,i will learn how you can use pluck method in laravel 8. we are show simple example of pluck query builder example in laravel 8. you can table to get array in values using laravel pluck method.

It can get value column and key using pluck method.pluck method to returned collection single column or specify a custom key column following example.

Example: 1

Here example single column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $ids = \DB::table('posts')->pluck('id');

   dd($ids);
}
Output
array:[
    0 => 1
    1 => 2
    2 => 3
   ]
Example: 2

>Here example specify a custom key column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $users  = User::pluck('name','id');

   dd($users);
}
Output
array:4 [
    1 => "abc"
    2 => "xyz"
    3 => "mno"
  ]
It will help you...

JQuery Get and Set Image Src Tutorial

JQuery Get and Set Image Src Tutorial

Hi Guys,

Today, I will learn you how to get and set image src in jquery. We will show easy example of jquery get and set image src.The attr() method to get and change the image source in jQuery.

Get Image Src

In this example,I will Use the below script to get image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $imgsrc = $('img').attr('src');
    alert($imgsrc);
   });
});
Set the Image Src

In this example,I will Use the below script to set image src.

$(document).ready(function() {
  $('.btn').click(function(){
    $("img").attr("src",'test.png');
  });
});
Full Example

Now,The following example will change the second image to the first image.

<html>
<head>
  <title> How to get and set image src attribute example</title>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
  <script>
    $(document).ready(function() {
      $('.btn').click(function(){
        $imgsrc = $('#first').attr('src');
        $("#second").attr("src",$imgsrc);
      });
    });
  </script>
  <style>
    .card{
      margin: 30px;
    }
  </style>
</head>
<body>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNSCowfKvdA_XwYJ4PViv9gQ-q50eeykM2E9FIdmSlIakgoW5QckWzOFc-WSBIZkBGkRXcefsoRVoPfP2UDM7qxUkoVc1IWSxhlZ0ZHx40BgJMO9eDkq1vQ18JWIhLW0C5W9owKiMdShmT/s0/Laravel+Custom+ENV+Variables+Tut.png" width="100" id="first" alt="Blog Image"">
  </div>
  <div class="card">
    <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpipA6pqFifEWR4qswk86MZvHOBRC9JKkJhtSTDDoQYfe-mDETt1DGzsLy1X_i9bwNBdHnM812ftqImUIZqvjtBponL-G36pDZ4wVWzhjfKphtGgVf5NaL5J5q_2mEO9MX_2XpPe5nu04Q/s0/laravel-email-vali.png" width="100" id="second" alt="Blog Image">
  </div>
  <button type="type" class="btn">Get & Set image src</button>
</body>
</html>

It Will help you....

Laravel 8 Pagination Tutorial Example

Laravel 8 Pagination Tutorial Example

Hi Guys,

Today, I will learn you how to create pagination with laravel 8.If you want to full example of laravel 8 pagination example blade. if you have question about laravel 8 pagination with user table then i will give simple and easy example with solution for you. i explained simply step by step laravel 8 pagination tutorial. let’s talk about pagination in laravel 8.

We know pagination is a primary requisite of each and every project. so if you are a beginner with laravel than you must know how to utilize pagination in laravel 8 and what is other function that can utilize with laravel 8 pagination.

Now, In this example i will explain you from scratch how to working with laravel pagination. so let's follow bellow step by step tutorial for creating simple example of pagination with laravel 8.

Step 1: Add Route

First all of we put one route in one for list users with pagination. So simply add both routes in your route file.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\ProductController;
  
/*
|--------------------------------------------------------------------------
| 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('product', [ProductController::class, 'index']);
Step 2: Create Controller

Same things as above for route, here we will add one new method for route. index() will return users with pagination data, so let's add bellow:

app/Http/Controllers/ProductController.php
<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Product::paginate(5);
        return view('product.index',compact('data'));
    }
}
Step 3: Create Blade File

After create ProductController you need to create index blade file and put bellow code with links() so it will generate pagination automatically. So let's put it.

resources/views/index.blade.php
    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
    <style type="text/css">
        .form-inline{
            display: inline;
        }
    </style>
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h3>Laravel 8 Pagination Example Tutorial</h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th>#</th>
                                    <th>Product Name</th>
                                    <th>Product Price</th>
                                    <th>Product Details</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(!empty($products) && $products->count())
                                    @foreach($products as $key => $product)
                                        <tr>
                                            <td>{{ ++$key }}</td>
                                            <td>{{ $product->name }}</td>
                                            <td>{{ $product->price }}</td>
                                            <td>{{ $product->details }}</td>
                                            <td>
                                                  <button class="btn btn-danger btn-icon">
                                                    <i class="far fa-trash-alt text-white" data-feather="delete"></i>
                                                  </button>
                                            </td>
                                        </tr>
                                    @endforeach
                                    @else
                                        <tr>
                                            <td colspan="10">There are no data.</td>
                                        </tr>
                                    @endif
                            </tbody>
                        </table>
                        {!! $products->links() !!}
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Now you can run and check this example. it is a very simple and basic example.

If you are using bootstrap then you have to add useBootstrap() on service provider as like bellow:

app\Providers\AppServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Support\ServiceProvider;
use Illuminate\Pagination\Paginator;
  
class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
    
    }
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Paginator::useBootstrap();
    }
}

If you need advance used of pagination then you can see bellow how to use.

Pagination with appends parameter

{!! $data->appends(['sort' => 'votes'])->links() !!}

Pagination with appends request all parameters

{!! $data->appends(Request::all())->links() !!}

You can also see in advance details from here: Laravel 8 Pagination.

It will help you..

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Laravel Treeview Create Multi Level Dynamic Menu Tutorial

Hii Dev,

In this blog, I will explain how can create dynamic multi level menu in laravel we will create example of multi level dynamic menu in laravel you can easy to make many level dynamic menu in laravel.

In this tutorial i simple create "menus" table and manage end level of parents and child menu with nested tree view structure in Laravel application. I use jquery for make tree view layout and child relationship with menu model for hierarchical data. I also add form for create new menu in tree view.I also create dynamic drop down menu using bootstrap nav.

If you are new in laravel then also you can do it simple and also simply customize it because this tutorial from scratch. You can simple following bellow step, you will multi level dynamic menu in your application as bellow preview and also you can check demo.

here following example step of multi level dynamic menu in laravel treeview

Step 1 : Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

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

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

following path: .env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create menus Table and Model

In this step we have to create migration and model for menus table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:model Menu -m
After this command you have to put bellow code in your migration file for create menus table. following path:/database/migrations/2020_01_10_102325_create_menus_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateMenusTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('menus', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->integer('parent_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('menus');
    }
}

Now we require to run migration be bellow command:

php artisan migrate

After you have to put bellow code in your model file for create Menu table.

following path:/app/Models/Menu.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    protected $fillable = ['title','parent_id'];

    public function childs() {
        return $this->hasMany('App\Menu','parent_id','id') ;
    }
}
Step 3: Create Route

In this is step we need to create route for tree menu show layout file , create menu for post method route and show dynamic menus.

following path:/routes/web.php
<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\MenuController;
    /*
    |--------------------------------------------------------------------------
    | 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('menus',[MenuController::class,'index']);
    Route::get('menus-show',[MenuController::class,'show']);
    Route::post('menus',[MenuController::class,'store'])->name('menus.store');
Step 4: Create Controller

Here this step now we should create new controller as MenuController,So run bellow command for generate new controller

php artisan make:controller MenuController

now this step, this controller will manage menu layout and create menu with validation with post request,bellow content in controller file. i added three method in this controller as listed bellow:

1)index() 2)store() 3)show() following path:/app/Http/Controllers/MenuController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Menu;

class MenuController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(){
   
       $menus = Menu::where('parent_id', '=', 0)->get();
       $allMenus = Menu::pluck('title','id')->all();
       return view('menu.menuTreeview',compact('menus','allMenus'));
   
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
       $request->validate([
           'title' => 'required',
        ]);

       $input = $request->all();
        $input['parent_id'] = empty($input['parent_id']) ? 0 : $input['parent_id'];
        Menu::create($input);
         return back()->with('success', 'Menu added successfully.');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show()
    {
        $menus = Menu::where('parent_id', '=', 0)->get();
        return view('menu.dynamicMenu',compact('menus'));
    }
}
Step 5: Create View

In this step, we have to create menu folder in total four blade file as listed bellow:

1)menuTreeview.blade.php

2)manageChild.blade.php

3)dynamicMenu.blade.php

4)menusub.blade.php

This both blade file will help to render menu tree structure, so let's create both file view file and put bellow code.

following path:/resources/views/menu/menuTreeview.blade.php
<!DOCTYPE html>
<html>
<head>
   <title>Multi Level Dynamic Menu In Laravel Treeview</title>
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.css">
   <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   <link href="/css/treeview.css" rel="stylesheet">
</head>
<body class="bg-dark">
<div class="container">
   <div class="row">
      <div class="col-md-10 offset-md-1 mt-4">
         <div class="card">
            <div class="card-header">
               <h5>Multi Level Dynamic Menu In Laravel Treeview</h5>
            </div>
            <div class="card-body">
               <div class="row">
                  <div class="col-md-6">
                     <h5 class="mb-4 text-center bg-success text-white ">Add New Menu</h5>
                     <form accept="{{ route('menus.store')}}" method="post">
                        @csrf
                         @if(count($errors) > 0)
                                  <div class="alert alert-danger  alert-dismissible">
                                      <button type="button" class="close" data-dismiss="alert">×</button>
                                      @foreach($errors->all() as $error)
                                              {{ $error }}<br>
                                      @endforeach
                                  </div>
                              @endif
                          @if ($message = Session::get('success'))
                           <div class="alert alert-success  alert-dismissible">
                               <button type="button" class="close" data-dismiss="alert">×</button>   
                                   <strong>{{ $message }}</strong>
                           </div>
                        @endif
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Title</label>
                                 <input type="text" name="title" class="form-control">   
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <div class="form-group">
                                 <label>Parent</label>
                                 <select class="form-control" name="parent_id">
                                    <option selected disabled>Select Parent Menu</option>
                                    @foreach($allMenus as $key => $value)
                                       <option value="{{ $key }}">{{ $value}}</option>
                                    @endforeach
                                 </select>
                              </div>
                           </div>
                        </div>
                        <div class="row">
                           <div class="col-md-12">
                              <button class="btn btn-success">Save</button>
                           </div>
                        </div>
                     </form>
                  </div>
                  <div class="col-md-6">
                     <h5 class="text-center mb-4 bg-info text-white">Menu List</h5>
                      <ul id="tree1">
                         @foreach($menus as $menu)
                            <li>
                                {{ $menu->title }}
                                @if(count($menu->childs))
                                    @include('menu.manageChild',['childs' => $menu->childs])
                                @endif
                            </li>
                         @endforeach
                        </ul>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </div>
</div>
<script src="/js/treeview.js"></script>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/manageChild.blade.php
  <ul>
  @foreach($childs as $child)
     <li>
         {{ $child->title }}
     @if(count($child->childs))
              @include('manageChild',['childs' => $child->childs])
          @endif
     </li>
  @endforeach
  </ul>

After This both blade file will help to render dynamic drop down menu view file, so let's create both file view file and put bellow code.

following path:/resources/views/menu/dynamicMenu.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://bootstrapthemes.co/demo/resource/bootstrap-4-multi-dropdown-hover-navbar/css/bootstrap-4-hover-navbar.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
<nav class="navbar navbar-expand-md navbar-light bg-light btco-hover-menu">
    <a class="navbar-brand" href="#">Nicesnippets.com</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
        <ul class="navbar-nav">
            @foreach($menus as $menu)
            <li class="nav-item dropdown">
                <a class="nav-link {{ count($menu->childs) ? 'dropdown-toggle' :'' }}" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                   {{ $menu->title }}
                </a>
                <ul class="dropdown-menu " aria-labelledby="navbarDropdownMenuLink">
                  @if(count($menu->childs))
                    @include('menu.menusub',['childs' => $menu->childs])
                  @endif
                </ul>
            </li>
            @endforeach
        </ul>
    </div>
</nav>
<div style="position: absolute; left:2%; top:55%;">
  <h2 class="bg-white p-2 shadow-lg rounded">Multi Level Dynamic Menu In Laravel Treeview</h2>
</div>
</body>
</html>

here following include blade fille

following path:/resources/views/menu/menusub.blade.php
 @foreach($childs as $child)
 <li>
      <a class="dropdown-item {{ count($child->childs) ? 'dropdown-toggle' :'' }}" href="#" style="border:1px solid #ccc;">{{ $child->title }}</a>
       @if(count($child->childs))
          <ul class="dropdown-menu">
              <li>
                 <a class="dropdown-item" href="#" style="position: absolute;">
                       @include('menu.menusub',['childs' => $child->childs])
                    </a>
                </li>
            </ul>
        @endif
   </li>
 @endforeach
Preview:Menu treeview hierarchical structure Step 6: Add CSS and JS File

In last step, we have to add one css file and one js file for treeview design. I simply use bootsnipp css and js code, so let's create css and js file as following path:

following path:public/css/treeview.css
.tree, .tree ul {
    margin:0;
    padding:0;
    list-style:none
}
.tree ul {
    margin-left:1em;
    position:relative
}
.tree ul ul {
    margin-left:.5em
}
.tree ul:before {
    content:"";
    display:block;
    width:0;
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    border-left:1px solid
}
.tree li {
    margin:0;
    padding:0 1em;
    line-height:2em;
    color:#369;
    font-weight:700;
    position:relative
}
.tree ul li:before {
    content:"";
    display:block;
    width:10px;
    height:0;
    border-top:1px solid;
    margin-top:-1px;
    position:absolute;
    top:1em;
    left:0
}
.tree ul li:last-child:before {
    background:#fff;
    height:auto;
    top:1em;
    bottom:0
}
.indicator {
    margin-right:5px;
}
.tree li a {
    text-decoration: none;
    color:#369;
}
.tree li button, .tree li button:active, .tree li button:focus {
    text-decoration: none;
    color:#369;
    border:none;
    background:transparent;
    margin:0px 0px 0px 0px;
    padding:0px 0px 0px 0px;
    outline: 0;
}

This is require js file

following path:public/js/treeview.js
$.fn.extend({
    treed: function (o) {
      
        var openedClass = 'glyphicon-minus-sign';
        var closedClass = 'glyphicon-plus-sign';
      
        if (typeof o != 'undefined'){
          if (typeof o.openedClass != 'undefined'){
            openedClass = o.openedClass;
          }
          if (typeof o.closedClass != 'undefined'){
            closedClass = o.closedClass;
          }
        }
      
        /* initialize each of the top levels */
        var tree = $(this);
        tree.addClass("tree");
        tree.find('li').has("ul").each(function () {
            var branch = $(this);
            branch.prepend("");
            branch.addClass('branch');
            branch.on('click', function (e) {
                if (this == e.target) {
                    var icon = $(this).children('i:first');
                    icon.toggleClass(openedClass + " " + closedClass);
                    $(this).children().children().toggle();
                }
            })
            branch.children().children().toggle();
        });
        /* fire event from the dynamically added icon */
        tree.find('.branch .indicator').each(function(){
            $(this).on('click', function () {
                $(this).closest('li').click();
            });
        });
        /* fire event to open branch if the li contains an anchor instead of text */
        tree.find('.branch>a').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
        /* fire event to open branch if the li contains a button instead of text */
        tree.find('.branch>button').each(function () {
            $(this).on('click', function (e) {
                $(this).closest('li').click();
                e.preventDefault();
            });
        });
    }
});
/* Initialization of treeviews */
$('#tree1').treed();

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

open bellow URL to create menu on your browser:

http://localhost:8000/menus

Now you can open bellow URL to dropdown nav menu on your browser:

http://localhost:8000/menus-show

It will help you...

Laravel Arr where() function Example

Laravel Arr where() function Example

Hi Dev,

Today,I will learn you how to use laravel array where() function example. We will show example of array where function in laravel.The Arr::where method filters an array using the given Closure:

Here, I will give you full example for simply Arr where() method in laravel as bellow.

Example
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\FileController;
use Illuminate\Support\Arr;

class HomeController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $array = [100, 'Laravel', 300, 'Php', 500];
        $filtered = Arr::where($array, function ($value, $key) {
                return is_string($value);
        });

        print_r($filtered);
        //[1 => 'Laravel', 3 => 'Php']

        $array2 = [100, '200', 300, '400', 500];

        $filtered2 = Arr::where($array2, function ($value, $key) {
            return is_string($value);
        });

        print_r($filtered2);
        // [1 => '200', 3 => '400']
    }
}
Output
"[1 => '200', 3 => '400']"
" [1 => 'Laravel', 3 => 'Php']"

It Will help you...

Laravel 8 Model Observers Example Tutorial

Laravel 8 Model Observers Example Tutorial

Hi Dev,

Nowdays,i will analyze you a way to use laravel 8 observers. this example will help you a way to use laravel 8 model observers. i would love to expose you what is observers in laravel 8. This tutorial will come up with simple instance of laravel eight model observers.

We can come up with very simple definition and use of laravel observers is, when you want to generate slug or auto generate precise identification or something like common sense add earlier than or after create document then observers will help you. i can come up with bellow events that provide via observers and easy instance bellow.

Here, i will give you complete instance for in reality model Observers the usage of Laravel eight as bellow.

Eloquent Hook

->Retrieved: after a record has been retrieved.

->Creating: before a record has been created.

->Created: after a record has been created.

->Updating: before a record is updated.

->Updated: after a record has been updated.

->Saving: before a record is saved (either created or updated).

->Saved: after a record has been saved (either created or updated).

->Deleting: before a record is deleted or soft-deleted.

->Deleted: after a record has been deleted or soft-deleted.

->Restoring: before a soft-deleted record is going to be restored.

->Restored: after a soft-deleted record has been restored.

Example:

Now In this blog,we will see simple example, i have one Food model and it has name, slug, price and unique_id column. so i need to create one record with name an price only. but when it's create i need to generate slug from name and auto generate unique_id.

app/Models/Food.php
<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
  
class Food extends Model
{
    use HasFactory;
  
    protected $fillable = [
        'name', 'price', 'slug', 'unique_id'
    ];
}

Create observers class for Food. So, create bellow command:

php artisan make:observer FoodObserver --model=Food
app/Observers/FoodObserver.php
<?php
  
namespace App\Observers;
  
use App\Models\Food;
  
class FoodObserver
{
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function creating(Food $food)
    {
        $food->slug = \Str::slug($food->name);
    }
  
    /**
     * Handle the Food "created" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function created(Food $food)
    {
        $food->unique_id = 'PR-'.$food->id;
        $food->save();
    }
  
    /**
     * Handle the Food "updated" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function updated(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function deleted(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "restored" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function restored(Food $food)
    {
          
    }
  
    /**
     * Handle the Food "force deleted" event.
     *
     * @param  \App\Models\Food  $food
     * @return void
     */
    public function forceDeleted(Food $food)
    {
          
    }
}

Register Observers class on provider.

app/Providers/EventServiceProvider.php
<?php
  
namespace App\Providers;
  
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
use App\Observers\FoodObserver;
use App\Models\Food;
  
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
  
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        Food::observe(FoodObserver::class);
    }
}

Create Demo Route:

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\FoodController;
  
/*
|--------------------------------------------------------------------------
| 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('food', [FoodController::class, 'index']);

Create Controller Route:

app/Http/Controllers/FoodController.php
<?php
  
namespace App\Http\Controllers;
  
use App\Models\Food;
use Illuminate\Http\Request;
  
class FoodController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
  
        $food = Food::create([
            'name' => 'Milk',
            'price' => 30
        ]);
  
        dd($food);
    }
}

Now you can run project.

It will help you...

Laravel WhereHas Eloquent Example

Laravel WhereHas Eloquent Example

Hi Guys,

Today,I will learn you how to laravel wherehas eloquent. you will learn about laravel eloquent whereHas() with example. we show example of wherehas eloquent in laravel.you can easily use laravel wherehas eloquent.

Here I will give you example of laravel wherehas eloquent.

Example WhereHas Eloquent

Now this example, If you need even more power, you may use the whereHas methods to put "where" conditions on your has queries.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Country;

class BlogController extends Controller
{  

  /**
   * Write code on Method
   *
   * @return response()
   */
   public function index()
   {
       $country = Country::whereHas('blogs', function($q){
                      $q->where('name', '=', 'Good Info');
                   })->get();  
       dd($country->toArray());
   }
}
Output
array:1 [
  0 => array:5 [
    "id" => 1
    "name" => "test"
    "blogs_id" => 1
    "created_at" => null
    "updated_at" => null
  ]
]

It will help you..

Laravel 8 Download File Example

Laravel 8 Download File Example

Hi Dev,

In this blog,I'm able to examine you how to download report in laravel 8. we are able to display instance of reaction download with document in laravel 8.We now and again require to go back reaction with download document from controller technique like generate invoice and deliver to download or and so on.Laravel eight provide us response() with down load approach that way we are able to do it.

Here, First argument of down load() I ought to give route of down load document. we will rename of download record through passing second argument of download(). We can also set headers of file with the aid of passing third argument.

So, first i am going to create new route for our instance as like bellow:

routes/web.php
<?php
use App\Http\Controllers\DownloadFileController;

/*
|--------------------------------------------------------------------------
| 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('/file-download', [DownloadFileController::class, 'index'])->name('file.download.index');

Now,I have to add one method "downloadFile()" in my DownloadFileController. If you don't have DownloadFileController then you can use your own controller as like bellow:

App\Http\Controllers\DownloadFileController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DownloadFileController extends Controller
{
    public function index()
    {
    	$filePath = public_path("dummy.pdf");
    	$headers = ['Content-Type: application/pdf'];
    	$fileName = time().'.pdf';

    	return response()->download($filePath, $fileName, $headers);
    }
}

It will help you...

Laravel Validation timezone Example

Laravel Validation timezone Example

Hi Guys,

Today, I will learn you to create validation timezone in laravel.we will show example of laravel validation timezone.The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

Here, I will give you full example for simply timezone validation in laravel bellow.

solution
$request->validate([
  'time_zone' => 'timezone',
]);
Route : routes/web.php
Route::get('form/create','FormController@index');
Route::post('form/store','FormController@store')->name('form.store');
Controller : app/Http/Controllers/FormController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Blade;
use App\Models\User;
use App\Models\Post;

class FormController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function create()
    {
        return view('form');
    }
    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $request->validate([
          'time_zone' => 'timezone'
        ]);
      dd('done');
    }
}
View : resources/views/form.php
<!DOCTYPE html>
<html>
<head>
  <title>From</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />
  <scrtimezonet src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></scrtimezonet>
  <scrtimezonet src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></scrtimezonet>
</head>
<body class="bg-dark">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-3">
        <div class="card mt-5">
          <div class="card-header">
            <div class="row">
              <div class="col-md-9">
                 Laravel Validation timezone Example
              </div>
              <div class="col-md-3 text-right">
                <a href="{{ route('form') }}" class="btn btn-sm btn-outline-primary">Back</a>
              </div>
            </div>
          </div>
          <div class="card-body">
            @if (count($errors) > 0)
                  <div class="row">
                      <div class="col-md-12">
                          <div class="alert alert-danger alert-dismissible">
                              <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                              @foreach($errors->all() as $error)
                              {{ $error }} <br>
                              @endforeach      
                          </div>
                      </div>
                  </div>
                @endif
              <form action="{{ route('from.store') }}" method="post">
                @csrf
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Your Timezone:</label>
                      <input name="time_zone" type="text" class="form-control">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-12">
                    <button class="btn btn-block btn-success">Submit</button>
                  </div>
                </div>
              </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>
</html>

It will help you...

Laravel Custom Middleware Tutorial Example

Laravel Custom Middleware Tutorial Example

Hi guys,

In this blog,I can create custom middleware in laravel, we are able to discover ways to create custom middleware in laravel utility and the way to use middleware in laravel based mission. truely create one custom middleware and take a look at language in query string.

clearly laravel middleware filter out all of the http request in laravel based totally tasks. as an instance when user is do any request that point middleware take a look at person is loggedin or now not and redirect therefore. Any person is not loggedin but he need to get entry to to dashboard or different things in projects that point middleware filter request redirect to consumer.

on this laravel middleware educational, we can supply a example of active or inactive users. Now we can name middleware in routes to restriction logged person to get right of entry to that routes, if he/she is blocked by way of admin.

In this laravel middleware tutorial, we will give a example of active or inactive users. Now we will call middleware in routes to restrict logged user to access that routes, if he/she is blocked by admin.

Step:1 Create Middleware

In this step, We have to create custom middleware in laravel based project. So let’s open your command prompt and run below command :

php artisan make:middleware CheckStatus
Step:2 Register Middleware

After successfully create middleware, go to app/http/kernel.php and register your custom middleware here :

app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    ....
 
    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        ....
        'checkStatus' => \App\Http\Middleware\CheckStatus::class,
    ];
}
?>
Step:3 Implement logic In Middleware

After successfully register your middleware in laravel project, go to app/http/middleware and implement your logic here :

app/Http/Middleware/CheckStatus.php
<?php
namespace App\Http\Middleware;
use Closure;

class CheckStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (auth()->user()->status == 'active') {
            return $next($request);
        }
            return response()->json('Your account is inactive');
 
    }
}
?>
Step:4 Create Route

In this step, simply we will create a route and use custom middleware here. Filter http every request and protect routes :

<?php
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\HomeController;

    /*
    |--------------------------------------------------------------------------
    | 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::middleware(['checkStatus'])->group(function(){
    Route::get('home', 'HomeController@home');
});
Step:5 Add Method in Controller

Now we will create one method name language and let’s check :

app/Http/Controllers/HomeController.php
<?php
 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 
 class HomeController extends Controller
 {
     public function home()
     {
         dd('You are active');
     }
 }
?>

We have successfully create custom middleware in laravel based project with simple example. run the example.

It Will help you....

Laravel Custom Forgot Password Email Function Example

Laravel Custom Forgot Password Email Function Example

Hi Guys,

Today, I will learn you how to custom forgot & reset password in laravel. we will show example of laravel custom forgot & reset password. you can easliy create custom forgot & reset password in laravel. This post will give you simple example of how to create custom forgot password in laravel. step by step explain laravel custom reset password email.

I will help to creating custom reset password function in php laravel. so basically, you can also create custom forget password with different models too.

Here, I will give you full example for simply laravel custom forgot & reset password as bellow.

Step 1: Install Laravel 8 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel Laravel8TypeheadTutorial
Step 2: Database Configuration

In this step, configure database with your downloded/installed laravel 8 app. So, you need to find .env file and setup database details as following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password
Step 3: Create "password_resets" table

basically, it will already created "password_resets" table migration but if it's not created then you can create new migration as like bellow code:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePasswordResetsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('password_resets', function (Blueprint $table) {
            $table->string('email')->index();
            $table->string('token');
            $table->timestamp('created_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('password_resets');
    }
}
Step 4: Create Route

In this is step we need to create custom route for forget and reset link. so open your routes/web.php file and add following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\Auth\ForgotPasswordController;
  
/*
|--------------------------------------------------------------------------
| 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('forget-password', [ForgotPasswordController::class, 'showForgetPasswordForm'])->name('forget.password.get');
Route::post('forget-password', [ForgotPasswordController::class, 'submitForgetPasswordForm'])->name('forget.password.post'); 
Route::get('reset-password/{token}', [ForgotPasswordController::class, 'showResetPasswordForm'])->name('reset.password.get');
Route::post('reset-password', [ForgotPasswordController::class, 'submitResetPasswordForm'])->name('reset.password.post');
Step 5: Create Controller

Now step, we need to create ForgotPasswordController and add following code on that file:

app/Http/Controllers/Auth/ForgotPasswordController.php
<?php 
  
namespace App\Http\Controllers\Auth; 
  
use App\Http\Controllers\Controller;
use Illuminate\Http\Request; 
use DB; 
use Carbon\Carbon; 
use App\Models\User; 
use Mail; 
use Hash;
use Illuminate\Support\Str;
  
class ForgotPasswordController extends Controller
{
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function showForgetPasswordForm()
      {
         return view('auth.forgetPassword');
      }
  
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function submitForgetPasswordForm(Request $request)
      {
          $request->validate([
              'email' => 'required|email|exists:users',
          ]);
  
          $token = Str::random(64);
  
          DB::table('password_resets')->insert([
              'email' => $request->email, 
              'token' => $token, 
              'created_at' => Carbon::now()
            ]);
  
          Mail::send('email.forgetPassword', ['token' => $token], function($message) use($request){
              $message->to($request->email);
              $message->subject('Reset Password');
          });
  
          return back()->with('message', 'We have e-mailed your password reset link!');
      }
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function showResetPasswordForm($token) { 
         return view('auth.forgetPasswordLink', ['token' => $token]);
      }
  
      /**
       * Write code on Method
       *
       * @return response()
       */
      public function submitResetPasswordForm(Request $request)
      {
          $request->validate([
              'email' => 'required|email|exists:users',
              'password' => 'required|string|min:6|confirmed',
              'password_confirmation' => 'required'
          ]);
  
          $updatePassword = DB::table('password_resets')
                              ->where([
                                'email' => $request->email, 
                                'token' => $request->token
                              ])
                              ->first();
  
          if(!$updatePassword){
              return back()->withInput()->with('error', 'Invalid token!');
          }
  
          $user = User::where('email', $request->email)
                      ->update(['password' => Hash::make($request->password)]);
 
          DB::table('password_resets')->where(['email'=> $request->email])->delete();
  
          return redirect('/login')->with('message', 'Your password has been changed!');
      }
}
Step 6: Email Configuration

In this step,we will add email configuration on env file, because we will send email to reset password link from controller.

.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp-mail.outlook.com
MAIL_PORT=587
MAIL_USERNAME=example@hotmail.com
MAIL_PASSWORD=123456789
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=example@hotmail.com
Step 7: Create Blade Files

Now in this step,we need to create blade files for layout, login, register and home page. so let's create one by one files.


<html>
<head>
    <title>Laravel</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <style type="text/css">
        @import url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);
  
        body{
            margin: 0;
            font-size: .9rem;
            font-weight: 400;
            line-height: 1.6;
            color: #212529;
            text-align: left;
            background-color: #f5f8fa;
        }
        .navbar-laravel
        {
            box-shadow: 0 2px 4px rgba(0,0,0,.04);
        }
        .navbar-brand , .nav-link, .my-form, .login-form
        {
            font-family: Raleway, sans-serif;
        }
        .my-form
        {
            padding-top: 1.5rem;
            padding-bottom: 1.5rem;
        }
        .my-form .row
        {
            margin-left: 0;
            margin-right: 0;
        }
        .login-form
        {
            padding-top: 1.5rem;
            padding-bottom: 1.5rem;
        }
        .login-form .row
        {
            margin-left: 0;
            margin-right: 0;
        }
    </style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar-laravel">
    <div class="container">
        <a class="navbar-brand" href="#">Laravel</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
   
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav ml-auto">
                @guest
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('login') }}">Login</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('register') }}">Register</a>
                    </li>
                @else
                    <li class="nav-item">
                        <a class="nav-link" href="{{ route('logout') }}">Logout</a>
                    </li>
                @endguest
            </ul>
        </div>
    </div>
</nav>
@yield('content')
</body>
</html>
resources/views/auth/forgetPassword.blade.php
@extends('layout')
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Reset Password</div>
                  <div class="card-body">
  
                    @if (Session::has('message'))
                         <div class="alert alert-success" role="alert">
                            {{ Session::get('message') }}
                        </div>
                    @endif
  
                      <form action="{{ route('forget.password.post') }}" method="POST">
                          @csrf
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Send Password Reset Link
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection
resources/views/auth/forgetPasswordLink.blade.php
@extends('layout')
  
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Reset Password</div>
                  <div class="card-body">
  
                      <form action="{{ route('reset.password.post') }}" method="POST">
                          @csrf
                          <input type="hidden" name="token" value="{{ $token }}">
  
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password" class="form-control" name="password" required autofocus>
                                  @if ($errors->has('password'))
                                      <span class="text-danger">{{ $errors->first('password') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password-confirm" class="col-md-4 col-form-label text-md-right">Confirm Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password-confirm" class="form-control" name="password_confirmation" required autofocus>
                                  @if ($errors->has('password_confirmation'))
                                      <span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Reset Password
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection
resources/views/email/forgetPassword.blade.php
<h1>Forget Password Email</h1>
   
<p>You can reset password from bellow link:</p>
<a href="{{ route('reset.password.get', $token) }}">Reset Password</a>
resources/views/auth/login.blade.php
@extends('layout')
  
@section('content')
<main class="login-form">
  <div class="cotainer">
      <div class="row justify-content-center">
          <div class="col-md-8">
              <div class="card">
                  <div class="card-header">Login</div>
                  <div class="card-body">
  
                      <form action="{{ route('login.post') }}" method="POST">
                          @csrf
                          <div class="form-group row">
                              <label for="email_address" class="col-md-4 col-form-label text-md-right">E-Mail Address</label>
                              <div class="col-md-6">
                                  <input type="text" id="email_address" class="form-control" name="email" required autofocus>
                                  @if ($errors->has('email'))
                                      <span class="text-danger">{{ $errors->first('email') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
                              <div class="col-md-6">
                                  <input type="password" id="password" class="form-control" name="password" required>
                                  @if ($errors->has('password'))
                                      <span class="text-danger">{{ $errors->first('password') }}</span>
                                  @endif
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <div class="col-md-6 offset-md-4">
                                  <div class="checkbox">
                                      <label>
                                          <input type="checkbox" name="remember"> Remember Me
                                      </label>
                                  </div>
                              </div>
                          </div>
  
                          <div class="form-group row">
                              <div class="col-md-6 offset-md-4">
                                  <div class="checkbox">
                                      <label>
                                          <a href="{{ route('forget.password.get') }}">Reset Password</a>
                                      </label>
                                  </div>
                              </div>
                          </div>
    
                          <div class="col-md-6 offset-md-4">
                              <button type="submit" class="btn btn-primary">
                                  Login
                              </button>
                          </div>
                      </form>
                        
                  </div>
              </div>
          </div>
      </div>
  </div>
</main>
@endsection

Now we are ready to run our example so run bellow command so quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/
It will help you...