Load more Data in Laravel using Ajax/Axios

tutspack laravel
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Hello Aritsans,

How are you doing? In this tutorial, I’ll show you how to implement load more data in Laravel using Ajax/Axios with a button click. I will show you everything step by step from scratch so that you can understand the main concept and implement other projects. So here we go.

Load more Data in Laravel using Ajax/Axios

Load more Data in Laravel using Ajax/Axios
Load more data by ajax

Step 1 – Install Laravel and connect with a database

composer create-project laravel/laravel Load_More

Step 2 – Make a Model

php artisan make:model Product -m

It will make Product.php and a migration file in your app/Http/Models folder and database/migrations folder.I make a demo product model. You can make as per your requirements. then go to migration file and paste the code inside the up() fucntion.

 public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('text');
            $table->float('price')->default(50);
            $table->timestamps();
        });
    }
Then run php artisan:migrate

Don’t forget to fillable migration columns in your Product.php file.

  protected $fillable = ['name','text','price'];

then you need to generate fake data using Seeder/Factory for testing purposes. I have made a tutorial on How to generate fake data in Laravel using factory and faker you can follow this tutorial to generate fake data.

Well, I assumed you have generated fake data. So go to thenext step.

Step 3 – Make a Controller

php artisan make:controller LoadMoreDataController

It will make the LoadMoreDataController.php file under the app/Http/Controllers folder. In this controller, we have to write all our all logic and conditions.

public function index(){
        return view('load.index');
    }

    public function loadMoreData(Request $request)
    {
        if ($request->id > 0) {
            //info($request->id);
            info('clicked');
            $data = Product::with('category')
                    ->where('id','<',$request->id)
                    ->orderBy('id','DESC')
                    ->limit(2)
                    ->get();
        } else {
            $data = Product::with('category')->limit(2)->orderBy('id', 'DESC')->get();
        }

        $output = '';
        $last_id = '';

        if (!$data->isEmpty()) {
            foreach ($data as $row) {
                $output .= '
                <div class="row">
                <div class="col-md-12">
                <span class="text-info">'.$row->id.'</span>
                <h3 class="text-info"><b>' . $row->name . '</b></h3>
                <p>' . $row->category->name . '</p>
                <hr />
                </div>
                </div>
                ';
                $last_id = $row->id ;
            }
            $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-success form-control" data-id="' . $last_id . '" id="load_more_button">Load More</button>

       </div>
       ';
        } else {
            $output .= '
       <div id="load_more">
        <button type="button" name="load_more_button" class="btn btn-info form-control">No Data Found</button>
       </div>
       ';
        }
        return $output;
    }

Copy and paste this two methods in this LoadMoreDataController . Ok Let’s jump the next step.

Step 4 – Make two Routes

Go to routes/web.php file. Write two line of code.

Route::get('load-data',[LoadMoreDataController::class,'index']);
Route::post('load-data', [LoadMoreDataController::class, 'loadMoreData'])->name('load-data');

Step 5 – Make a View to show your output

I have made a view file in layouts/views folder. You have to link up the bootstrap, jquery, Axios files I have added those in my layout file which I extended. Now copy and paste this code.

@extends('layouts.app')

@section('title','Load Data')

@section('content')
<div class="container my-3">
    <h2 class="text-center">Load More Data By Ajax</h2>
    <hr>
</div>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-8">
            <div id="loadData"></div>
        </div>
    </div>
</div>
@stop

@push('script')
    <script>
        function loadMoreData(id=0){
            axios.post('{{ route("load-data") }}',{ id : id})
            .then(res => {
               //console.log(res.data);
                   $('#load_more_button').remove();
                   $('#loadData').append(res.data);
            })
            .catch(err => {
                console.log(err);
            })
        }
        loadMoreData(0);
        $(document).on('click', '#load_more_button', function(){
        var id = $(this).data('id');
        //console.log(id);
        $('#load_more_button').html('<b>Loading...</b>');
        loadMoreData(id);
    });

    </script>
@endpush

now run php aritsan serve and hit http://127.0.0.1:8000/load-data

Hope It will helps you.

Read More : https://tutspack.com/crud-example-with-repository-design-pattern-in-laravel/


Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  

About Anisur Rahman Shahin

Hello. My name is Shahin. I'm a tech enthusiast guy. Personally, I’m Optimistic and always in hurry kinda person. I'm a freelance web developer. I am working at Zakir Soft as Laravel Developer. My Portfolio website: https://devshahin.com/

View all posts by Anisur Rahman Shahin →

One Comment on “Load more Data in Laravel using Ajax/Axios”

Leave a Reply

Your email address will not be published. Required fields are marked *