Laravel 11 CRUD and Image Upload Tutorial Example

Laravel 11 CRUD and Image Upload Tutorial Example

Welcome guys! In this Laravel 11 crud with image upload guide, we will show you how to create crud (create, read, update, delete) operation with an image upload in laravel 11 applications.

If you want to create a post, category, job, vacancy, inventory, slider, carousel etc crud application in Laravel and also add image upload feature to it, Laravel has provided many built-in methods for the same, which you can use, and it can be done easily in just a few minutes.

In this example guide, we will create a vacancies crud operation application with an image upload feature in laravel 11 applications.

Steps for Laravel 11 CRUD with Image Upload Tutorial Example

Here are:

Step 1 – Laravel 11 Installation

If you do not have installed laravel 11 on your server, Just run the composer create-project --prefer-dist laravel/laravel FirstLaravelCRUD on cmd or terminal window to download & install latest laravel 11 application setup into your server:

composer create-project --prefer-dist laravel/laravel FirstLaravelCRUD

Step 2 – Database Configuration

Now, open the .env file from the laravel application root directory and configure your database details; Something like this:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=name_of_your_database
DB_USERNAME=name_of_your_database_user
DB_PASSWORD=password_of_your_database_user

Step 3 – Creating Migration and Model File

Run the php artisan make:model Vacancy -m command on cmd or terminal window to create migration and model file for crud operation with image upload application:

php artisan make:model Vacancy -m

Now open create_vacancies_table.php file from /database/migrations/ folder and update the up() function to create table into your database:

    public function up(): void
    {
        Schema::create('vacancies', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->string('image');
            $table->timestamps();
        });
    }

Run the php artisan migrate command on cmd to create tables into your configured database with laravel applications:

php artisan migrate

Step 4 – Creating CRUD with Image Upload Routes

Open web.php file from routes folder, and create add,edit,delete and list routes for the crud application in it; something like this:

use App\Http\Controllers\VacancyCRUDController;
  
Route::get('vacancies', [VacancyCRUDController::class, 'index']);
Route::get('add-vacancy', [VacancyCRUDController::class, 'create']);
Route::post('save-vacancy', [VacancyCRUDController::class, 'store']);
Route::get('edit/{id}', [VacancyCRUDController::class, 'edit']);
Route::post('update', [VacancyCRUDController::class, 'update']);
Route::get('delete/{id}', [VacancyCRUDController::class, 'destroy']);

Step 5 – Creating CRUD Operation Methods in Controller

Run php artisan make:controller VacancyCRUDController command on cmd to create controller file:

php artisan make:controller VacancyCRUDController

Now, open VacancyCRUDController.php file from app/http/controllers folder and create some methods into it to handle crud operation with database; something like this:

<?php
  
namespace App\Http\Controllers;
   
use App\Models\Vacancy;
use Illuminate\Http\Request;
  
class VacancyCRUDController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data['vacancies'] = Vacancy::orderBy('id','desc')->paginate(5);
    
        return view('index', $data);
    }
     
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }
    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
            'description' => 'required'
        ]);

        $imageName = $request->file('image')->getClientOriginalName();
        $request->file('image')->storeAs('public/images', $imageName);

        $Vacancy = new Vacancy;
        $Vacancy->title = $request->title;
        $Vacancy->description = $request->description;
        $Vacancy->image = $imageName;
        $Vacancy->save();
     
        return redirect('vacancies')
               ->with('success','Vacancy has been created successfully.');
    }
     
     
    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Vacancy  $Vacancy
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        
        $data['vacancy'] = Vacancy::find($id);
    
        return view('edit', $data);
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Vacancy  $Vacancy
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $request->validate([
            'title' => 'required',
            'description' => 'required',
        ]);
        
        $id = $request->id;

        $Vacancy = Vacancy::find($id);

        // Check if a new image file was uploaded
        if ($request->hasFile('image')) {
            // Delete the old image file if it exists
            if ($Vacancy->image) {
                \Storage::delete('public/images/' . $Vacancy->image);
            }
            // Store the new image file
            $imageName = $request->file('image')->getClientOriginalName();
            $request->file('image')->storeAs('public/images', $imageName);
            $Vacancy->image = $imageName;
        }

        $Vacancy->title = $request->title;
        $Vacancy->description = $request->description;
        $Vacancy->save();
    
              return redirect('vacancies')
               ->with('success','Vacancy has been updated successfully.');
    }
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Vacancy  $Vacancy
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $Vacancy = Vacancy::where('id',$id)->delete();
    
         return redirect('vacancies')
               ->with('success','Vacancy has been deleted successfully.');
    }
}

Step 6 – Create CRUD Views File

Go to resources/views folder and, and then create index.blade.php, create.blade.php and edit.blade.php files.

Now, open index.blade.php file and create list table in it to show a list vancancies from database in it; something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 11 CRUD and Image Upload Example Tutorial - Tutsmake.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container mt-2">
<div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 11 CRUD and Image Upload Example Tutorial - Tutsmake.com</h2>
            </div>
            <div class="pull-right mb-2">
                <a class="btn btn-success" href="{{ url('add-vacancy') }}"> Create Vacancy</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered">
        <tr>
            <th>S.No</th>
            <th>Title</th>
            <th>Image</th>
            <th>Description</th>
            <th width="280px">Action</th>
        </tr>
       
        @foreach ($vacancies as $vc)
        <tr>
            <td>{{ $vc->id }}</td>
            <td>{{ $vc->title }}</td>
            <td><img src="{{ asset('storage/images/'.$vc->image) }}" alt="Your Image" width="100px" height="100px"></td>
            <td>{{ $vc->description }}</td>
            <td>
                <form action="{{ url('delete/'.$vc->id) }}" method="get">
    
                    <a class="btn btn-primary" href="{{ url('edit/'.$vc->id) }}">Edit</a>
   
                    @csrf
                    @method('get')
      
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
        </tr>
        @endforeach
  
    </table>
  
    {!! $vacancies->links() !!}
</body>
</html>

Next open create.blade.php file and create add vacancy form in it, to create a add vacancy in database; Something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Image Upload with Crud in Laravel 11 - Tutsmake.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
<div class="container mt-2">
  
<div class="row">
    <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 11 CRUD Operation Example Tutorial - Tutsmake.com</h2>
            </div>
        <div class="pull-left mb-2">
            <h2>Add Vacancy</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ url('vacancies') }}"> Back</a>
        </div>
    </div>
</div>
   
  @if(session('status'))
    <div class="alert alert-success mb-1 mt-1">
        {{ session('status') }}
    </div>
  @endif
   
<form action="{{ url('save-vacancy') }}" method="POST" enctype="multipart/form-data">
    @csrf
        
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Title:</strong>
                <input type="text" name="title" class="form-control" placeholder="Title">
               @error('title')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Description:</strong>
                 <input type="text" name="description" class="form-control" placeholder="Description">
                @error('description')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>        
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Vacancy Poster Image:</strong>
                 <input type="file" name="image" class="form-control">
                @error('image')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>
    <div class="col-xs-6 col-sm-6 col-md-6 mt-2">
        <button type="submit" class="btn btn-primary ml-3">Submit</button>
    </div>
    </div>
   
</form>
</body>
</html>

Now, Open edit.blade.php file and create edit vacancy form in it to edit vacancy data from database; something like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Laravel 11 Image Upload with CRUD Operation - Tutsmake.com</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    </head>
<body>
<div class="container mt-2">
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel 11 Image Upload with CRUD Operation Example Tutorial - Tutsmake.com</h2>
            </div>
            <div class="pull-left">
                <h2>Edit vacancy
                </h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ url('vacancies') }}" enctype="multipart/form-data"> Back</a>
            </div>
        </div>
    </div>
   
  @if(session('status'))
    <div class="alert alert-success mb-1 mt-1">
        {{ session('status') }}
    </div>
  @endif
  
    <form action="{{ url('update') }}" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="hidden" name="id" value="{{ $vacancy->id }}">
   
         <div class="row">
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Title:</strong>
                    <input type="text" name="title" value="{{ $vacancy
                    ->title }}" class="form-control" placeholder="please enter title">
                    @error('title')
                     <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
            </div>
 
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Description:</strong>
                    <input type="text" name="description" value="{{ $vacancy
                    ->description }}" class="form-control" placeholder="Please enter description">
                    @error('description')
                     <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
                    @enderror
                </div>
            </div>

         <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Vacancy Poster Image:</strong>
                 <input type="file" name="image" class="form-control">
                 <br>
                 <img src="{{ asset('storage/images/'.$vacancy->image) }}" alt="Your Image" width="100px" height="100px">
                @error('image')
                  <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
               @enderror
            </div>
        </div>

             <div class="col-xs-6 col-sm-6 col-md-6 mt-2">
              <button type="submit" class="btn btn-primary ml-3">Submit</button>
          </div>
          
        </div>
   
    </form>
</div>
</body>
</html>

Step 7 – Run and Test Application

Run php artisan serve command on cmd to start this application server, and you can test it on your browser:

php artisan serve

Now, open your browser and type the following URL into it for testing:

http://127.0.0.1:8000/vacancies

Conclusion

We hope that with the help of the example tutorial guide you have learned how to create Image Upload feature with Laravel 11 CRUD Operation application.

Recommended Guides

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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