article

Saturday, May 6, 2023

Laravel 10 Click Load More Data

Laravel 10 Click Load More Data

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laraveldb
DB_USERNAME=root
DB_PASSWORD=

Create Model and Migration

C:\xampp\htdocs\laravel\laravelproject>php artisan make:model Post -m

A new file named Post.php will be created in the app directory and database/migrations directory to generate the table in our database
app/Models/Post.php

//app/Models/Post.php
<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    
class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'body', 'slug'
    ];
}
database\migrations\create_posts_table.php
//database\migrations\create_posts_table.php
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('slug');
            $table->text('body');
            $table->timestamps();
        });
    }
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};
Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate
Migration table created successfully.

check database table

Create Factory Class

php artisan make:factory PostFactory --model=Post
C:\xampp\htdocs\laravel\laravel10project>php artisan make:factory PostFactory --model=Post
database\factories\PostFactory.php

//database\factories\PostFactory.php
<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use App\Models\Post;
use Illuminate\Support\Str;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Post>
 */
class PostFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Post::class;
      
    /**
     * Define the model's default state.
     *
     * @return array

     */
    public function definition()
    {
        return [
            'title' => $this->faker->text(),
            'slug' => Str::slug($this->faker->text()),
            'body' => $this->faker->paragraph()
        ];
    }
}
Open terminal, execute the below commands to generate the test data:
php artisan tinker
C:\xampp\htdocs\laravel\laravel10project>php artisan tinker
App\Models\Post::factory()->count(50)->create();

Create Controller
C:\xampp\htdocs\laravel\laravel10project>php artisan make:controller PostController

app\Http\Controllers\PostController.php
//app\Http\Controllers\PostController.php
<?php
     
namespace App\Http\Controllers;
     
use Illuminate\Http\Request;
use App\Models\Post;
     
class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::paginate(6);
  
        if ($request->ajax()) {
            $view = view('data', compact('posts'))->render();
  
            return response()->json(['html' => $view]);
        }
  
        return view('posts', compact('posts'));
    }
}
Create View File
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery
https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js
resources/views/posts.blade.php

//resources/views/posts.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Click Load More Data</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
    <h1>Laravel 10 Click Load More Data</h1>
  
    <div id="data-wrapper">
        <div class="row">
        @include('data')
        </div>
    </div>
  
    <div class="row text-center" style="padding:20px;">
        <button class="btn btn-success load-more-data">Load More Data...</button>
    </div>
  
    <div class="auto-load text-center" style="display: none;">
        <div class="d-flex justify-content-center">
            <div class="spinner-border" role="status">
                <span>Loading...</span>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
    var ENDPOINT = "{{ route('posts.index') }}";
    var page = 1;
  
    $(".load-more-data").click(function(){
        page++;
        LoadMore(page);
    });
    function LoadMore(page) {
        $.ajax({
                url: ENDPOINT + "?page=" + page,
                datatype: "html",
                type: "get",
                beforeSend: function () {
                    $('.auto-load').show();
                }
            })
            .done(function (response) {
                console.log(response);
                if (response.html == '') {
                    $('.auto-load').html("End :(");
                    return;
                }
                $('.auto-load').hide();
                $("#data-wrapper").append("<div class='row'>" + response.html + "</div>");
            })
            .fail(function (jqXHR, ajaxOptions, thrownError) {
                console.log('Server error occured');
            });
    }
</script>
</body>
</html>
resources/views/data.blade.php
//resources/views/data.blade.php
@foreach ($posts as $post)
<div class="col-4">
    <div class="card">
      <img src="https://placehold.co/400x250" class="card-img-top" alt="...">
      <div class="card-body">
        <h5 class="card-title">{{ $post->id }}  : {{ $post->title }}</h5>
        <p class="card-text">{!! $post->body !!}</p>
      </div>
    </div>
</div>
@endforeach
routes/web.php
//routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

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

Route::get('posts',[PostController::class,'index'])->name('posts.index');
Run C:\xampp\htdocs\laravel\laravel10project>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000/posts

Related Post