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...

Laravel Calculate Time Difference Between Two Dates In Hours And Minutes

Laravel Calculate Time Difference Between Two Dates In Hours And Minutes

Hello Dev,

In this blog, i'm able to explain the way to calculate time difference among two dates in hours and mins in laravel,we will show calculate time distinction among dates in hours and mins.we can carbon the use of time difference between dates in hours and minutes.

I'm able to show difference among dates in hours and minutes the use of diffForHumans and diff techniques in laravel we will diffForHumans technique to reveal distinction between two dates in hours and mins.

Here following instance of calculate time distinction between two dates in hours and minutes in laravel

Example: 1

Now the example of diffForHumans method using time difference between two dates in hours and minutes in laravel.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{

    $startTime = Carbon::parse('2020-02-11 04:04:26');
    $endTime = Carbon::parse('2020-02-11 04:36:56');

    $totalDuration = $endTime->diffForHumans($startTime);
    dd($totalDuration);
}
Output
"32 minutes after"
Example: 2

Now the example of diff method using time difference between two dates in hours and minutes in laravel.

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{

    $startTime = Carbon::parse('2020-02-11 04:04:26');
    $endTime = Carbon::parse('2020-02-11 04:36:56');

    $totalDuration =  $startTime->diff($endTime)->format('%H:%I:%S')." Minutes";
    dd($totalDuration);
}
Output
"00:32:30 Minutes"

It will help you...

Laravel Please Provide A Valid Cache Path Error

Hello guys,

In this blog , i'm able to display you the way to solution Please provide a valid Cache pathblunders in laravel.a few errors happens on deploying laravel initiatives on webservers. So don’t worry about that this mistake “please provide a legitimate cache route laravel“.

The cause for occurring this mistake “please offer a legitimate cache direction laravel” error occurs. because internal your laravel mission, does not have some directories/folders. The directories and folders are the subsequent:

->YourProjectFolder/storage/framework/

->sessions

->views

->cache

This blog will provide you 3 solutions to fix this “please provide a valid cache path laravel” on your server or virtual host.

Solution: 1

In the first solution, you can create a framework folder inside your laravel-project-name/storage/ directory by using the following command:

cd storage/
mkdir -p framework/{sessions,views,cache}

Then set permissions to the directory. To allow Laravel to write data in the above-created directory. So run the following command on your command prompt:

cd storage/
chmod -R 775 framework
chown -R www-data:www-data framework
Solution No: 2

In the solution number 2, You can create mutually directories inside your laravel project folder.

So, Navigate to your project root directory and open Storage folder.

Then, Create framework directory/folder inside the storage folder.

After that, create the following directories inside the framework folder.

->sessions

->views

->cache

cache/data:- Inside cache folder, create a new directory/folder named data.

Finally, open your terminal and run the following command to clear all the cache:

php artisan cache:clear
Solution No: 3

In this solution number 3, open your terminal and run the following

commands:
sudo mkdir storage/framework
sudo mkdir storage/framework/sessions
sudo mkdir storage/framework/views
sudo mkdir storage/framework/cache
sudo mkdir storage/framework/cache/data

sudo chmod -R 777 storage 

It will help you..

Laravel Ajax Form Submit With Validation Example

Laravel Ajax Form Submit With Validation Example

Hi Dev,

In this blog,i will indicates how you can submit the form the usage of ajax with jquery validation(patron facet) in laravel. we can ajax post form after validation in laravel. you could clean laravel ajax shape publish. you could submit the shape the usage of jquery and with out the complete page refresh. whilst we publish an ajax form in laravel, we will upload csrf token in ajax request.

here following example to laravel ajax shape submit with validation.

Step 1: Create Model and Migration

here this step, we will create one model and migration name Post. Use the below following command and create it

php artisan make:model Post -m

Next,Open post migration file and put the below code. here following path of migration file

Path: /database/migrations/2020_01_02_095534_create_posts_table.php
<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Next, go to app/Post.php and open post model file and put the below code. here following path of model fille Path:/app/Post.php
<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['title','body'];
}
Step 2: Create Route

Create two routes one for show form and the second route send data to the server:

here following path of route fille

Path:/routes/web.php
Route::get('ajax-form-submit', 'PostController@index');
Route::post('save-form', 'PostController@store');
Step 3:Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller PostController 
Step 4:Controller Code

here this step,we will create two methods inside the controller first index method is used to display contact form and second store method is used to store data in the mysql database

here following path of Controller fille

Path:/app/Http/Controllers/PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
   
  public function index()
  {
  	return view('ajaxPostForm');
  }

  public function store(Request $request)
  {
     $input = $request->all();
     $request->validate([
       'title' => 'required',
       'body' => 'required'
     ]);
     $check = Post::create($input);
     $arr = array('msg' => 'Something goes to wrong. Please try again lator', 'status' =>false);
     if($check){ 
        $arr = array('msg' => 'Successfully Form Submit', 'status' => true);
     }
    return response()->json($arr);
  }
}
Step 5:Create a blade view

In this step, we will create one blade file name ajaxPostForm.blade.php.

In this ajax form, we will implement a jquery submit handler. first, we will validate form using jquery validation and second is to submit an ajax form using submit handler.

here following path of blade fille

Path:/resources/views/ajaxPostForm.blade.php
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Post Form </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/additional-methods.min.js"></script>
  <style>
   .error{ color:red; } 
  </style>
</head>
<body>
   <div class="container">
      <div class="row">
         <div class="col-md-6 mt-3 offset-md-3">
            <div class="card">
               <div class="card-header bg-dark text-white">
                  <h6>laravel Ajax Form Submission Example </h6>
               </div>
               <div class="card-body">
                  <form id="post-form" method="post" action="javascript:void(0)">
                     @csrf
                     <div class="row">
                        <div class="col-md-12">
                           <div class="alert alert-success d-none" id="msg_div">
                                   <span id="res_message"></span>
                              </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Title<span class="text-danger">*</span></label>
                              <input type="text" name="title" placeholder="Enter Title" class="form-control">
                              <span class="text-danger p-1">{{ $errors->first('title') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <div class="form-group">
                              <label>Body<span class="text-danger">*</span></label>
                              <textarea class="form-control" rows="3" name="body" placeholder="Enter Body Text"></textarea>
                              <span class="text-danger">{{ $errors->first('body') }}</span>
                           </div>
                        </div>
                     </div>
                     <div class="row">
                        <div class="col-md-12">
                           <button type="submit" id="send_form" class="btn btn-block btn-success">Submit</button>
                        </div>   
                     </div>
                  </form>
               </div>
            </div>
         </div>
      </div>
   </div>
</body>
<script>
   if ($("#post-form").length > 0) {
    $("#post-form").validate({
      
    rules: {
      title: {
        required: true,
        maxlength: 50
      },
      body: {
        required: true,
        maxlength: 250
      }
    },
    messages: {
      title: {
        required: "Please Enter Name",
        maxlength: "Your last name maxlength should be 50 characters long."
      },
      body: {
        required: "Please Enter Body",
        maxlength: "Your last body maxlength should be 250 characters long."
      },
    },
    submitHandler: function(form) {
     $.ajaxSetup({
          headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $('#send_form').html('Sending..');
      $.ajax({
        url: '/save-form' ,
        type: "POST",
        data: $('#post-form').serialize(),
        success: function( response ) {
            $('#send_form').html('Submit');
            $('#res_message').show();
            $('#res_message').html(response.msg);
            $('#msg_div').removeClass('d-none');
 
            document.getElementById("post-form").reset(); 
            setTimeout(function(){
            $('#res_message').hide();
            $('#msg_div').hide();
            },10000);
        }
      });
    }
  })
}
</script>
</html>

We will validate form data before submit, check validation like mobile number contains only digits not accept the character. The name filed contains 50 characters only. we will use post method in laravel ajax with csrf token

Step 6:Start Server

In this step, we will use the php artisan serve command.

php artisan serve

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

http://localhost:8000/ajax-form-submit

It will help you...

How To Set Bcc And CC Mail Address In Laravel ?

How To Set Bcc And CC Mail Address In Laravel ?

Hi Guys,

Today,I will learn you how to set bcc And cc Mail Address In Laravel Mail. I can show you set bcc (blind carbon copy) and cc (carbon copy) mail address in laravel mail.You can easy get laravel mail in cc and bcc here the example

Laravel Send Mail using Mailable Class Example

You can tell Set Bcc And Cc Mail Address In Laravel Mail before learn how to send Mail here this link

Link:https://itwebtuts.blogspot.com/2021/04/laravel-8-send-email-example-tutorial.html You are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients all within a single, chained method call: Solution Here, this cc() and bcc() method to you can set bcc and cc mail address in laravel mail.
 /**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function itTestMail()
{
    $myUsers = 'xzy@gmail.com';
    $myMoreUsers ='abc@gmail.com';
    $evenMyMoreUsers = 'pqr@gmail.com';
    
    Mail::to($myUsers)
        ->cc($moreMyUsers)
        ->bcc($evenMyMoreUsers)
        ->send(new MyTestMail());
    
    dd("Mail Send Successfully");
}
It will help you...

Laravel Ajax CRUD Tutorial Using Datatable Example

Laravel Ajax CRUD Tutorial Using Datatable Example

Hello Dev,

Here, i'm able to manual you step by step ajax crud operations in laravel eight with modal & pagination. we are able to create jquery ajax crud with modals using datatables js in laravel eight. we can definitely write jquery ajax request for crud with yajra datatable laravel 8.

We will use bootstrap modal for create new statistics and update new statistics. we can use aid routes to create crud (create examine replace delete) software in laravel eight.we are able to use yajra datatable to list a records with pagination, sorting and filter.

I will provide you little by little manual to create ajax crud instance with laravel. you simply need to observe few step to get c.r.u.d with modals and ajax. you could effortlessly use along with your laravel mission and smooth to customise it.

Step 1: Install Laravel 8 To start with we need to get clean Laravel eight version application using bellow command, So open your terminal OR command set off and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Database Configuration

In 2d step, we will make database configuration as an example database call, username, password etc for our crud utility of laravel 8. So allow's open .env report and fill all information 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 3: Install Yajra Datatable

We need to install yajra datatable composer package for datatable, so you can install using following command:

composer require yajra/laravel-datatables-oracle
After that you need to set providers and alias. config/app.php
.....
'providers' => [
	....
	Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
	....
	'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
Step 4: Create Migration Table

we are going to create ajax crud application for product. so we have to create migration for "products" table using Laravel 8 php artisan command, so first fire bellow command:

php artisan make:migration create_products_table --create=products

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 products table.

/database/migrations/2020_01_10_102325_create_products_table.php
<?php
 
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
  
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Now you have to run this migration by following command:

php artisan migrate
Step 5: Create Route

Here, we need to add resource route for product ajax crud application. so open your "routes/web.php" file and add following route.

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

Route::resource('ajaxproducts',ProductAjaxController::class);
Step 6: Add Controller and Model

In this step, now we should create new controller as ProductAjaxController. So run bellow command and create new controller.

So, let's copy bellow code and put on ProductAjaxController.php file.

app/Http/Controllers/ProductAjaxController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use DataTables;

class ProductAjaxController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Product::latest()->get();
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){
   
                           $btn = '<a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>';
   
                           $btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip"  data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>';
    
                            return $btn;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
      
        return view('productAjax');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        Product::updateOrCreate(['id' => $request->product_id],
                ['name' => $request->name, 'detail' => $request->detail]);        
   
        return response()->json(['success'=>'Product saved successfully.']);
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Product::find($id)->delete();
     
        return response()->json(['success'=>'Product deleted successfully.']);
    }
}

Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:

app/Product.php
<?php

namespace App\Models;

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

class Product extends Model
{
     protected $fillable = [
        'name', 'detail'
    ];
}
Step 7: Add Blade Files

In last step. In this step we have to create just blade file. so we need to create only one blade file as productAjax.blade.php file.

So let's just create following file and put bellow code.

resources/views/productAjax.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax CRUD Tutorial Using Datatable </title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
    <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script>
</head>
<style type="text/css">
    .container{
        margin-top:150px;
    }
    h4{
        margin-bottom:30px;
    }
</style>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="row">
                <div class="col-md-12 text-center">
                    <h4>Laravel 8 Ajax CRUD Tutorial Using Datatable </h4>
                </div>
                <div class="col-md-12 text-right mb-5">
                    <a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
                </div>
                <div class="col-md-12">
                    <table class="table table-bordered data-table">
                        <thead>
                            <tr>
                                <th>No</th>
                                <th>Name</th>
                                <th>Details</th>
                                <th width="280px">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
   
<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="productForm" name="productForm" class="form-horizontal">
                    <input type="hidden" name="product_id" id="product_id">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-12">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
                        </div>
                    </div>
     
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Details</label>
                        <div class="col-sm-12">
                            <textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
                        </div>
                    </div>
      
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
    
</body>
    
<script type="text/javascript">
    $(function () {
     
    $.ajaxSetup({
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    
    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('ajaxproducts.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'name', name: 'name'},
            {data: 'detail', name: 'detail'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });
     
    $('#createNewProduct').click(function () {
        $('#saveBtn').val("create-product");
        $('#product_id').val('');
        $('#productForm').trigger("reset");
        $('#modelHeading').html("Create New Product");
        $('#ajaxModel').modal('show');
    });
    
    $('body').on('click', '.editProduct', function () {
        var product_id = $(this).data('id');
        $.get("{{ route('ajaxproducts.index') }}" +'/' + product_id +'/edit', function (data) {
            $('#modelHeading').html("Edit Product");
            $('#saveBtn').val("edit-user");
            $('#ajaxModel').modal('show');
            $('#product_id').val(data.id);
            $('#name').val(data.name);
            $('#detail').val(data.detail);
        })
    });
    
    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
    
        $.ajax({
            data: $('#productForm').serialize(),
            url: "{{ route('ajaxproducts.store') }}",
            type: "POST",
            dataType: 'json',
            success: function (data) {
                $('#productForm').trigger("reset");
                $('#ajaxModel').modal('hide');
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
                $('#saveBtn').html('Save Changes');
            }
        });
    });

    $('body').on('click', '.deleteProduct', function (){
        var product_id = $(this).data("id");
        var result = confirm("Are You sure want to delete !");
        if(result){
            $.ajax({
                type: "DELETE",
                url: "{{ route('ajaxproducts.store') }}"+'/'+product_id,
                success: function (data) {
                    table.draw();
                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });
        }else{
            return false;
        }
    });
});
</script>
</html>

Now you can test it by using following command:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/ajaxproducts

It will help you...

Laravel User Active and Inactive Status Example

Laravel User Active and Inactive Status Example

Hi Men,

In this Blog, I can explain a way to create functionality to crate active and inactive user in laravel. I provide you with a complete instance of energetic and inactive user status in laravel. we can enforce exchange fame using ajax with bootstrap toggle button in laravel. we will replace user status lively inactive with boolean information type with zero and 1.

I almost require to create repute exchange capability in out laravel . it is probably require for user in laravel, product repute, category fame, and many others. we've continually yes or no, enable or disabled, lively and inactive and many others. you can do it this toggle stuff using jquery ajax.

We are able to create a customers listing web page and provide bootstrap toggle button the use of bootstrap-toggle js. so you can effortlessly allow and disabled it. using bootstrap-toggle js exchange occasion we can write jquery ajax code and fire get or submit request to trade person statue discipline on database.

Right Here following the example of active and inactive status in laravel

Step 1 : Install Laravel 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
Step 2: Create Route

In this is step we need to create route for active and inactive status layout file in laravel

following path:/routes/web.php
Route::get('users', 'UserStatusController@index');
Route::get('userChangeStatus', 'UserStatusController@userChangeStatus');
Step 3: Create Controller

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

php artisan make:controller UserStatusController

After this step,we should create new controller as UserController. this controller will manage layout and getting data request and return response, so put bellow content in controller file:

following path:/app/Http/Controllers/UserStatusController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserStatusController extends Controller
{
	 /**
     * Responds with a welcome message with instructions
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::get();
        return view('users',compact('users'));
    }
  
    /**
     * Responds with a welcome message with instructions
     *
     * @return \Illuminate\Http\Response
     */
    public function userChangeStatus(Request $request)
    {
    	\Log::info($request->all());
        $user = User::find($request->user_id);
        $user->status = $request->status;
        $user->save();
  
        return response()->json(['success'=>'Status change successfully.']);
    }
}
Step 4: Create View

In Last step,we will write design code here and put following code

following path:/resources/views/users.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Active and Inactive Status in Laravel? </title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" ></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css"  />
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
</head>
<body class="bg-info">
    <div class="container">
      <div class="panel panel-default" style="margin-top: 40px">
        <div class="panel-heading">
          <h2>How to Active and Inactive Status in Laravel?  </h2>
        </div>
        <div class="panel-body">
          <table class="table table-bordered">
              <thead>
                 <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Status</th>
                 </tr> 
              </thead>
              <tbody>
                 @foreach($users as $user)
                    <tr>
                       <td>{{ $user->name }}</td>
                       <td>{{ $user->email }}</td>
                       <td>
                          <input data-id="{{$user->id}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $user->status ? 'checked' : '' }}>
                       </td>
                    </tr>
                 @endforeach
              </tbody>
          </table>
        </div>
      </div>
    </div>
</body>
<script>
  $(function() {
    $('.toggle-class').change(function() {
        var status = $(this).prop('checked') == true ? 1 : 0; 
        var user_id = $(this).data('id'); 
         console.log(status);
        $.ajax({
            type: "GET",
            dataType: "json",
            url: '/userChangeStatus',
            data: {'status': status, 'user_id': user_id},
            success: function(data){
              console.log(data.success)
            }
        });
    })
  })
</script>
</html> 

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

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/users

It will help you...

Laravel 8 Full Text Search with Ajax Example

Laravel 8 Full Text Search with Ajax Example

Hi Men,

In this blog,I'm able to examine you how to use complete text search using ajax in laravel.you could easy and surely use complete textual content search using ajax in laravel.

This is one greater put up on Laravel 8 and on this post you may discover a way to put into effect complete text search in Laravel eight framework through the use of Ajax with Searchable Laravel package. if you desired to discover ways to make full text seek in you Laravel 8 software? If sure, then this put up will help you may gaining knowledge of this subject matter.

Here in this submit we've got percentage academic on a way to create complete textual content search with the aid of using "nicolaslopezj/searchable" package with Ajax in Laravel eight framework. So, consumer can get searchable facts on internet page without refresh of net page, due to the fact here we have use Ajax in Laravel eight framework.

You need to realize what's complete textual content search. So, complete textual content seek is a one type of seek method, which seek data on each word of request to your database. most of engines like google has been used complete text search technique for search records on each word of seek request and seek result on internet web page. it is more advance level for search a information in database.

Download Laravel 8 framework

For make any Laravel 8 application, first we need to download and install Laravel 8 framework. So, in this step of Laravel 8 tutorial, we have to go command prompt and go directory in which we want to download load and install Laravel 8 framework. We have to write and run following command.

composer create-project --prefer-dist laravel/laravel laravel-8	
Download and Install Searchable Package

In this Laravel 8 tutorial, We need to make Full text search feature in Laravel 8 application. For this here we have use "nicolaslopezj/searchable" package. For this we have to go command prompt and run following command. This command will download and install this searchable package in Laravel 8 application.

composer require nicolaslopezj/searchable
Make Database Connection

Before making Mysql Database connection, first we need to create table in your database. For this, you have to run following SQL script.

CREATE TABLE `full_text_searches` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) NOT NULL,
  `Gender` varchar(30) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `full_text_searches`
--

INSERT INTO `full_text_searches` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom'),
(144, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(143, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(141, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(142, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(140, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States'),
(139, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(138, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(136, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(137, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(145, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States');

Now we want to make database connection in Laravel 6 framework. For this we have to open .env and in this file we have to define Mysql Database configuration.

.env
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=
Create Model

Here we have use Model class for builder database query, so for this we have to create model class, so we have go to command prompt and write following command.

php artisan make:model Full_text_search --migration
app/Models/Full_text_search.php
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Nicolaslopezj\Searchable\SearchableTrait;

class Full_text_search extends Model
{
    use Notifiable;
    use SearchableTrait;

    /**
     * Write code on searchable
     *
     * 
     */
    protected $searchable = [
        'columns' => [
            'full_text_searches.CustomerName'  => 10,
            'full_text_searches.Gender'   => 10,
            'full_text_searches.Address'   => 10,
            'full_text_searches.City'    => 10,
            'full_text_searches.PostalCode'  => 10,
            'full_text_searches.Country'   => 10,
            'full_text_searches.id'    => 10,
        ]
    ];

    /**
     * Write code on fillable
     *
     * 
     */
    protected $fillable = [
        'CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country',
    ];
}
Set Controller Method Route

In Laravel 8 application, we need to set the route of all controller method, for this we have to open routes/web.php file and in this file we have define route which you can find below.

routes/web.php
<?php
<?php
  
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Full_text_search_Controller;
  
/*
|--------------------------------------------------------------------------
| 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('full-text-search', [Full_text_search_Controller::class,'index']);
Route::post('full-text-search/action', [Full_text_search_Controller::class,'action'])->name('full-text-search.action');
?>
Create Controller

For handle HTTP request we need to create controller in Laravel 6 application. For create controller here we have use compser command for this we have go to command prompt and run following command.

php artisan make:controller Full_text_search_Controller
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\FullTextSearch;
use DataTables;

class FullTextSearchController extends Controller
{   
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('fullText.fullTextSearch');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function action(Request $request)
    {
      if($request->ajax())
      {
        $data = FullTextSearch::search($request->get('full_text_search_query'))->get();
        return response()->json($data);
      }
    }
}
Create View Blade File

For display output in browser, we need to create blade file in resources/views folder. Here we have create full_text_search.blade.php file in this folder. In this file first we have to create on search box for search data and then after we have create one table. After this we have to write Ajax request, which will send ajax request to action() method of controller and it will received full text search data in json format and convert into HTML table and display on web page using jQuery. This Ajax request will be trigger when we have click on search button. Whole source code of this file you can get below.

resources/views/full_text_search.blade.php
<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Full Text Search in Laravel using Ajax Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Full Text Search in Laravel using Ajax Example</h3>
     <br />
     <div class="row">
      <div class="col-md-6">
       <input type="text" name="full_text_search" id="full_text_search" class="form-control" placeholder="Search" value="">
      </div>
      <div class="col-md-2">
       @csrf
       <button type="button" name="search" id="search" class="btn btn-success">Search</button>
      </div>
     </div>
     <br />
     <div class="table-responsive">
    <table class="table table-bordered table-hover">
        <thead>
         <tr>
            <th>Customer Name</th>
            <th>Gender</th>
            <th>Address</th>
                  <th>City</th>
                  <th>Postal Code</th>
                  <th>Country</th>
         </tr>
     </thead>
     <tbody></tbody>
    </table>
   </div>
        </div>
 </body>
</html>


<script>
$(document).ready(function(){

 load_data('');

 function load_data(full_text_search_query = '')
 {
  var _token = $("input[name=_token]").val();
  $.ajax({
   url:"{{ route('full-text-search.action') }}",
   method:"POST",
   data:{full_text_search_query:full_text_search_query, _token:_token},
   dataType:"json",
   success:function(data)
   {
    var output = '';
    if(data.length > 0)
    {
     for(var count = 0; count < data.length; count++)
     {
      output += '<tr>';
      output += '<td>'+data[count].CustomerName+'</td>';
      output += '<td>'+data[count].Gender+'</td>';
      output += '<td>'+data[count].Address+'</td>';
      output += '<td>'+data[count].City+'</td>';
      output += '<td>'+data[count].PostalCode+'</td>';
      output += '<td>'+data[count].Country+'</td>';
      output += '</tr>';
     }
    }
    else
    {
     output += '<tr>';
     output += '<td colspan="6">No Data Found</td>';
     output += '</tr>';
    }
    $('tbody').html(output);
   }
  });
 }

 $('#search').click(function(){
  var full_text_search_query = $('#full_text_search').val();
  load_data(full_text_search_query);
 });

});
</script>
Run Laravel 8 Application

After all code is ready, lastly we need to start Laravel 6 framework server. For this we have to go command prompt and write following command.

php artisan serve

This command will start server and give you base url of your application. For test above code you have write following url in your browser.

localhost:8000/full-text-search

It will help you...

Laravel 8 Ajax Pagination Example

Laravel 8 Ajax Pagination Example

Hi Men,

In this blog, I can provide an explanation for you the way to create jquery ajax pagination in laravel eight, we will create ajax pagination in laravel 8. i will show a little by little easy ajax pagination in laravel 8.

A pagination helps us to load few records every time, that way cannot broken net web page due to masses of information. in case you are making pagination and do it the use of ajax then it a better way. Ajax Pagination load most effective your table facts rather than the entire page. So ajax pagination is very useful.

We simply create "product" table the use of migration command and add a few dummy records. After that, we are able to create one direction for display view and write code jquery ajax on blade report. So, you need to simply follow beneath step and you will get virtually ajax pagination in laravel 8

Right here, I give you full example of ajax pagination instance grade by grade like create laravel eight undertaking, migration, model, direction, blade file and so forth. so that you have to just observe few steps.

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

1.Database Password

1.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 products Table and Model

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

php artisan make:model Product -m

After this command you have to put bellow code in your migration file for create products table.

following path: /database/migrations/2020_01_10_102325_create_products_table.php
<?php

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

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

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

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 products table.

following path:/app/Models/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{	
    /**
    * Run the migrations.
    *
    * @return void
    */
    protected $fillable = [
        'name',
    ];
}
Step 3: Create Route

In this is step we need to create route for ajax pagination layout file

following path:/routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\AjaxPaginationController;
  
/*
|--------------------------------------------------------------------------
| 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('pagination-ajax','AjaxPaginationController@ajaxPagination')->name('ajax.pagination');
Step 4: Create Controller

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

php artisan make:controller AjaxPaginationController

now this step, this controller will manage ajax pagination layout bellow content in controller file.following fille path

following path:/app/Http/Controllers/AjaxPaginationController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class AjaxPaginationController extends Controller
{
  /**
  * Display a listing of the resource.
  *
  * @return \Illuminate\Http\Response
  */
  public function ajaxPagination(Request $request)
  {
    $products = Product::paginate(5);
  
    if ($request->ajax()) {
        return view('presult', compact('products'));
    }
  
    return view('ajaxPagination',compact('products'));
  }
}
Step 5: Create Blade Files

In Last step, let's create ajaxPagination.blade.php (resources/views/ajaxPagination.blade.php) for layout and lists all product code here and put following code

following path:/resources/views/ajaxPagination.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Ajax Pagination Example </title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
  
<body class="bg-dark">
<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <div class="card-header">
                    <h5>Laravel 8 Ajax Pagination Example </h5>
                </div>
                <div class="card-body" id="tag_container">
                   @include('presult')
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(window).on('hashchange', function() {
        if (window.location.hash) {
            var page = window.location.hash.replace('#', '');
            if (page == Number.NaN || page <= 0) {
                return false;
            }else{
                getData(page);
            }
        }
    });
    
    $(document).ready(function()
    {
        $(document).on('click', '.pagination a',function(event)
        {
            event.preventDefault();
  
            $('li').removeClass('active');
            $(this).parent('li').addClass('active');
  
            var myurl = $(this).attr('href');
            var page=$(this).attr('href').split('page=')[1];
  
            getData(page);
        });
  
    });
  
    function getData(page){
        $.ajax(
        {
            url: '?page=' + page,
            type: "get",
            datatype: "html"
        }).done(function(data){
            $("#tag_container").empty().html(data);
            location.hash = page;
        }).fail(function(jqXHR, ajaxOptions, thrownError){
              alert('No response from server');
        });
    }
</script>
  
</body>
</html>
resources/views/presult.blade.php
<table class="table table-bordered">
    <thead>
        <tr>
            <th width="100px">Id</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($products as $value)
        <tr>
            <td>{{ $value->id }}</td>
            <td>{{ $value->name }}</td>
        </tr>
        @endforeach
    </tbody>
</table>
{!! $products->render() !!}

Now you have some dummy data on your products table before run this example. Now we are ready to run our example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/pagination-ajax

It will help you...