How to Create a Laravel CRUD Application with Image Upload

How to Create a Laravel CRUD Application with Image Upload

Laravel is a powerful PHP framework that simplifies web development tasks, including CRUD (Create, Read, Update, Delete) operations. In this tutorial, we’ll walk through building a simple CRUD application with image upload functionality.

Prerequisites

Before we begin, ensure you have the following installed:

  • PHP (>= 7.3)
  • Composer
  • Laravel Installer
  • MySQL Database
  • Basic knowledge of Laravel and MVC architecture

Step 1: Set Up a New Laravel Project

First, create a new Laravel project using the following command:

composer create-project --prefer-dist laravel/laravel laravel-crud-image-upload

Navigate to the project directory:

cd laravel-crud-image-upload

Step 2: Configure the Database

Open the .env file and update the database credentials:

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

Run the migrations to create the necessary tables:

php artisan migrate

Step 3: Create a Model and Migration

Generate a model and migration for the Product entity, which will include fields for name, description, and image:

php artisan make:model Product -m

Open the migration file located in database/migrations/ and update it:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->string('image')->nullable();
        $table->timestamps();
    });
}

Run the migration:

php artisan migrate

Step 4: Create a Controller

Generate a controller for handling CRUD operations:

php artisan make:controller ProductController --resource

Open the ProductController located in app/Http/Controllers/ and add the following methods:

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    // Display a listing of the resource
    public function index()
    {
        $products = Product::all();
        return view('products.index', compact('products'));
    }

    // Show the form for creating a new resource
    public function create()
    {
        return view('products.create');
    }

    // Store a newly created resource in storage
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $imageName = time().'.'.$request->image->extension();  
        $request->image->move(public_path('images'), $imageName);

        Product::create([
            'name' => $request->name,
            'description' => $request->description,
            'image' => $imageName,
        ]);

        return redirect()->route('products.index')->with('success', 'Product created successfully.');
    }

    // Display the specified resource
    public function show(Product $product)
    {
        return view('products.show', compact('product'));
    }

    // Show the form for editing the specified resource
    public function edit(Product $product)
    {
        return view('products.edit', compact('product'));
    }

    // Update the specified resource in storage
    public function update(Request $request, Product $product)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        if ($request->hasFile('image')) {
            $imageName = time().'.'.$request->image->extension();  
            $request->image->move(public_path('images'), $imageName);
            $product->image = $imageName;
        }

        $product->name = $request->name;
        $product->description = $request->description;
        $product->save();

        return redirect()->route('products.index')->with('success', 'Product updated successfully.');
    }

    // Remove the specified resource from storage
    public function destroy(Product $product)
    {
        $product->delete();
        return redirect()->route('products.index')->with('success', 'Product deleted successfully.');
    }
}

Step 5: Create Views

Create a folder named products inside the resources/views/ directory. Inside this folder, create the following Blade files:

  • index.blade.php (List all products)
  • create.blade.php (Create a new product)
  • edit.blade.php (Edit an existing product)
  • show.blade.php (Show product details)

Here’s an example of create.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Product</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1>Create Product</h1>
        <form action="{{ route('products.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" name="name" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="description">Description</label>
                <textarea name="description" class="form-control" required></textarea>
            </div>
            <div class="form-group">
                <label for="image">Image</label>
                <input type="file" name="image" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</body>
</html>

Step 6: Set Up Routes

Open the routes/web.php file and define the routes for the ProductController:

use App\Http\Controllers\ProductController;

Route::resource('products', ProductController::class);

Step 7: Test the Application

Start the Laravel development server:

php artisan serve

Visit http://127.0.0.1:8000/products in your browser. You should be able to:

  • Create a new product with an image.
  • View the list of products.
  • Edit or delete a product.

Conclusion

You’ve successfully built a Laravel CRUD application with image upload functionality! This is a great starting point for more complex applications. You can extend this by adding features like user authentication, pagination, or validation enhancements.

Happy coding! 🚀

0 Comments