Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Laravel 11 CRUD Example Tutorial with Search, Image and Pagination

Laravel 11 CRUD Example Tutorial with Search, Image and Pagination

Aman Jain, July 5, 2024July 5, 2024

In this article, we’ll delve into Laravel and explore the implementation of CRUD operations alongside essential features like Search, Image uploading, and Pagination. CRUD, an acronym for Create, Read, Update, and Delete, forms the backbone of database management in web applications across all programming paradigms. This tutorial covers these fundamental operations and extends into advanced topics such as form validation, unique validation, Flash messaging, and managing uploaded images.

To begin our Laravel 11 project, we’ll set up our environment and establish a connection to MySQL for database operations. Our next step involves creating a resourceful controller, which automates the generation of routes for adding, editing, and deleting data.

A key aspect of this tutorial is the integration of pagination and search functionalities into our list page. Pagination enhances user experience by dividing large datasets into manageable pages, while the search feature allows users to quickly locate information based on criteria such as email and title.

For data entry, our form includes fields for title, email, body text, and image uploading. Unlike many other Laravel CRUD tutorials, we’ll cover the often overlooked but crucial aspects of handling unique validations and managing image uploads.

Join us as we explore Laravel 11 CRUD operations, including Search, Image uploading, and Pagination, in a detailed, step-by-step manner

Step 1: Create a laravel project

First step is to create the Laravel project using composer command or you can also read the Simplest Way to Install Laravel and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel crud

Step 2: Configure database

Next step is to configure the database for our project, table and data. So open .env or if file not exist then rename .env.example file to .env file in root folder and change below details

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

Step 3: Create Model and Migration

If you have table and large data already then you can skip this step but if you are beginner and trying to implement Crud then in this step we are creating a model and migration using artisan command

php artisan make:model Article -m

Above command will create two files one is migration and other one is model. open migration file which is located at database/migrations/timestamp_create_articles_table.php and edit the schema as below

  public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('email')->unique();;
            $table->string('title');
            $table->string('body')->nullable();;
            $table->string('image');
            $table->timestamps();
        });
    }

Run migration using artisan command in command line

php artisan migrate

Output of above command

Migrating: 2022_06_25_112800_create_articles_table
Migrated:  2022_06_25_112800_create_articles_table (45.63ms)

Step 4 : Create a controller

Next, Create the resource controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller ArticleController --resource

Now, add the controller logic for pagination

<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $articles = Article::when($request->has("title"), function ($q) use ($request) {
            return $q->where("title", "like", "%" . $request->get("title") . "%");
        })
            ->when($request->has("email"), function ($q) use ($request) {
                return $q->where("email", "like", "%" . $request->get("email") . "%");
            })
            ->paginate(10);

        return view('articles.list ', ['articles' => $articles]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('articles.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => "required",
            'email' => "required|email|unique:articles",
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:4096',
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }
       

        //  save image and name in database
        $Article = new Article();
        $Article->title = $request->title;
        $Article->email = $request->email;
        $file = $request->file("image")->store("public/articles");
        $Article->image = str_replace("public/","storage/",$file);
        $Article->body  = $request->body;
        $Article->save();
        return redirect()->route("articles.index")
            ->with('success', 'You have successfully created the article.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return view('articles.update', ["article" => Article::find($id)]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $Article=Article::find($id);

        $validator = Validator::make($request->all(), [
            'title' => "required",
            'email' => "required|email|unique:articles,email," . $id,
            'image' => [Rule::requiredIf(function ()use($Article){

                if (!empty($Article->image)) {
          
                   return false;
                }
          
                  return true;
          
               }),'image','mimes:jpeg,png,jpg,gif,svg','max:4096'],
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withInput()->withErrors($validator->errors());
        }

       

        //  save image and name in database
        $Article->title = $request->title;
        $Article->email = $request->email;
        if($request->hasFile("image")){
            $file = $request->file("image")->store("public/articles");
            $Article->image = str_replace("public/","storage/",$file);
        }
        $Article->body  = $request->body;
        $Article->save();
        return redirect()->route("articles.index")
            ->with('success', 'You have successfully updated the article.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Article::find($id)->delete();
        return redirect()->route("articles.index")
            ->with('success', 'You have successfully deleted the article.');
    }
}

So as you can see we have created multiple methods and created their definitions in the method. So in index method we have simply fetched the all records from atricles table using model Article along with searching.

Then, we have store method where we have defined the validation rules and the definition logic for add the data in article table along with image uploading.

Next, we have edit and destroy method to update and delete the models.

So to configure the images we need tp create Symblink as follow

$file = $request->file("image")->store("uploads/images");

Now run artisan command to run Symblink

php artisan storage:link

You can read Full article here How to access and setup storage files after upload in laravel ?

Step 5 : Create the views

Here in this step we will create 3 views as follow

  1. resources/views/articles/list.blade.php – To list all articles
  2. resources/views/articles/create.blade.php – To create article
  3. resources/views/articles/update.blade.php – To update the article

So here is the code for resources/views/articles/list.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 11 CRUD Example Tutorial with Search, Image and Pagination - Readerstacks </title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body class="antialiased">
    <div class="container">
        <!-- main app container -->
        <div class="readersack">
            <div class="container">
                <div class="row">
                    <div class="col-md-12 ">
                        <h3>Laravel 11 CRUD Example Tutorial with Search, Image and Pagination - Readerstacks</h3>
                        @if ($message = Session::get('success'))
                        <div class="alert alert-success alert-block">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                            <strong>{{ $message }}</strong>
                        </div>

                        @endif
                        <a class='btn btn-info' href='{{url("articles/create")}}'>Add New</a>

                        <div id="search">

                            <form id="searchform" name="searchform">
                                <div class="row">

                                    <div class="form-group col-3">
                                        <label>Search by Title</label>
                                        <input type="text" name="title" value="{{request()->get('title','')}}" class="form-control" />


                                    </div>
                                    <div class="form-group col-3">
                                        <label>Search by Email</label>
                                        <input type="text" name="email" value="{{request()->get('email','')}}" class="form-control" />


                                    </div>
                                    <div class="form-group col-3">
                                        <label>Search by body</label>
                                        <input type="text" name="body" value="{{request()->get('body','')}}" class="form-control" />


                                    </div>
                                </div>
                                <button class='btn btn-success'>Search</button>
                            </form>


                        </div>
                        <div id="pagination_data">
                            <table class="table table-striped table-dark table-bordered">
                                <tr>
                                    <th>Sr No.</th>
                                    <th>Title</th>
                                    <th>Email</th>
                                    <th>Image</th>
                                    <th>Body</th>

                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                                @foreach($articles as $article)
                                <tr>
                                    <td>{{$article->id}}</td>
                                    <td>{{$article->email}}</td>

                                    <td>{{$article->title}}</td>
                                    <td><img src="{{url($article->image)}}" width=100 /></td>
                                    <td>{{substr($article->body,0,50)}}</td>
                                    <td>{{$article->created_at}}</td>
                                    <td>

                                        <a href="{{route('articles.edit',$article->id) }}" class="btn btn-success">Edit</a>
                                        <form action="{{ route('articles.destroy',$article->id) }}" method="Post">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger">Delete</button>
                                        </form>


                                    </td>
                                </tr>
                                @endforeach
                            </table>
                            <div id="pagination">
                                {{ $articles->links() }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- credits -->
        <div class="text-center">
            <p>
                <a href="#" target="_top">Laravel 11 CRUD Example Tutorial with Search, Image and Pagination                </a>
            </p>
            <p>
                <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
            </p>
        </div>
    </div>

</body>

</html>

Here is the main code where we called $articles->links() and foreach loop to show the data.

And then create file

resources/views/articles/create.blade.php

<!DOCTYPE html>
<html>

<head>
    <title> Laravel 11 CRUD Example Tutorial with Search, Image and Pagination  - readerstacks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2> Laravel 11 CRUD Example Tutorial with Search, Image and Pagination -readerstacks.com</h2>
            </div>
            <div class="panel-body">

                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                </div>

                @endif
                @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
                <br><br>
                <form action="{{ url('articles') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="row">

                        <div class="col-md-4">
                            <label>Title</label>
                            <input type="text" placeholder="Title" value="{{ old('title') }}" name="title" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Email</label>
                            <input type="email" placeholder="Email" value="{{ old('email') }}" name="email" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Body</label>
                            <input type="text" placeholder="Body" value="{{ old('body') }}" name="body" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Image</label>
                             <input type="file" placeholder="Image" name="image" id="imgInp">
                              <img style="visibility:hidden"  id="prview" src=""  width=100 height=100 />
                      
                    </div>
                     </div>
                    <div class="row">



                        <div class="col-md-6">
                            <button type="submit" class="btn btn-success">Add</button>
                        </div>

                    </div>
                </form>
                
        </div>
    </div>
</body>
<script>
imgInp.onchange = evt => {
  const [file] = imgInp.files
  if (file) {
    prview.style.visibility = 'visible';

    prview.src = URL.createObjectURL(file)
  }
}
</script>
</html>


and final file for update resources/views/articles/update.blade.php

<!DOCTYPE html>
<html>

<head>
    <title> Laravel 11 CRUD Example Tutorial with Search, Image and Pagination  - readerstacks.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>

<body>
    <div class="container">

        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2> Laravel 11 CRUD Example Tutorial with Search, Image and Pagination -readerstacks.com</h2>
            </div>
            <div class="panel-body">

                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <strong>{{ $message }}</strong>
                </div>

                @endif
                @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
                <br><br>
                <form action="{{ route('articles.update',$article->id) }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <div class="row">

                        <div class="col-md-4">
                            <label>Title</label>
                            <input type="text" placeholder="Title" value="{{ old('title',$article->title) }}" name="title" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Email</label>
                            <input type="email" placeholder="Email" value="{{ old('email',$article->email) }}" name="email" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Body</label>
                            <input type="text" placeholder="Body" value="{{ old('body',$article->body) }}" name="body" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label>Image</label>
                            <input type="file" placeholder="Image" name="image" id="imgInp">
                            <img id="prview" src="{{url($article->image)}}" width=100 height=100 />


                        </div>
                    </div>
                    <div class="row">



                        <div class="col-md-6">
                            <button type="submit" class="btn btn-success">Update</button>
                        </div>

                    </div>
                </form>
                </div>
    </div>
</body>
<script>
imgInp.onchange = evt => {
  const [file] = imgInp.files
  if (file) {
    prview.style.visibility = 'visible';

    prview.src = URL.createObjectURL(file)
  }
}
</script>
</html>

Step 6 : Create Route

Last and final step is to create the route for our resource controller to serve the CRUD

<?php

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


Route::resource('articles', "\App\Http\Controllers\ArticleController");

You can read more about resource controller How to create resource controller in Laravel 8 ?

Now run the the application using php artisan serve and check our implementation

php artisan serve

Laravel CRUD with search pagination validation and image
Laravel CRUD with search pagination validation and image
Laravel CRUD with search pagination validation and image
Laravel CRUD with search pagination validation and image
Laravel CRUD with search pagination validation and image
Laravel CRUD with search pagination validation and image

Related

Php Laravel 11 CRUDimagelaravellaravel 10paginationSearchvalidation

Post navigation

Previous post
Next post

Related Posts

Php Use Soft Delete to Temporary (Trash) Delete the Records in Laravel

Use Soft Delete to Temporary (Trash) Delete the Records in Laravel 9 ?

June 14, 2022June 14, 2022

Soft delete in laravel is use to hide the record from users by keeping the data in the database. In laravel we use Soft Delete to Temporary (Trash) Delete the Records. There is many purpose of soft delete like deleting the user for admin but keep all the information in…

Read More
Php get last insert id in laravel

How to get last insert id in laravel with example ?

March 5, 2022February 22, 2024

In this article i will learn you to get last insert id in laravel, In laravel we can execute our queries in two ways first is using the laravel eloquent and other one is DB builder. so in the both pattern we can get the last inserted i in laravel….

Read More
Javascript Laravel Customized Autocomplete JQuery UI

Laravel Customized Autocomplete JQuery UI

July 12, 2022July 12, 2022

Laravel Customized Autocomplete JQuery UI is useful when we want live search of bulk data. Autocomplete search is mostly work of javascript and when we want to fetch live data from database then we require the intervention of laravel to provide the data in json response. In this tutorial we…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
  • Understanding High Vulnerabilities in Software: A Week of Insights
  • Blocking Spam Requests with LaraGuard IP: A Comprehensive Guide
  • Enhancing API Development with Laravel API Kit
  • Exploring the Future of Web Development: Insights from Milana Cap
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version