How to upload image in laravel | websolutioncode.com
How to upload image in laravel | websolutioncode.com

How to upload image in laravel

Upload image in Laravel is a common task in web development. Laravel makes it easy to handle file uploads with its built-in features. Explore a comprehensive, step-by-step tutorial showcasing practical code examples for uploading images in Laravel.

Step 1: Set Up Laravel Project

Make sure you have Laravel installed on your system. If not, you can install it using Composer:

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

Change into the project directory:

cd image-upload-laravel

Step 2: Configure Database (Optional)

If you haven’t set up your database yet, open the .env file in the project root and configure the database settings:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Run the migrations to create the necessary tables:

php artisan migrate

Step 3: Create Model, Controller, and Migration

Generate a model, controller, and migration for the image uploads:

php artisan make:model Image -m
php artisan make:controller ImageController

Open the migration file created in the database/migrations folder and define the images table schema with columns like name and path. Then, run the migration:

php artisan migrate

Step 4: Update Model and Controller

Open the Image.php model file in the app directory and define the fillable attributes:

// app/Models/Image.php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'path'];
}

Next, update the ImageController.php file in the app/Http/Controllers directory. Add methods for displaying the upload form and handling the image upload:

// app/Http/Controllers/ImageController.php
namespace App\Http\Controllers;

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

class ImageController extends Controller
{
    public function index()
    {
        $images = Image::all();
        return view('index', compact('images'));
    }

    public function create()
    {
        return view('upload');
    }

    public function store(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

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

        Image::create(['name' => $imageName, 'path' => '/images/'.$imageName]);

        return redirect()->route('image.index')->with('success', 'Image uploaded successfully.');
    }
}

Step 5: Create Blade Views

Create two Blade views in the resources/views directory: upload.blade.php for the upload form and index.blade.php for displaying uploaded images.

<!-- resources/views/upload.blade.php -->
<form action="{{ route('image.store') }}" method="post" enctype="multipart/form-data">
    @csrf
    <input type="file" name="image" accept="image/*">
    <button type="submit">Upload</button>
</form>
<!-- resources/views/index.blade.php -->
@foreach($images as $image)
    <img src="{{ $image->path }}" alt="{{ $image->name }}" style="max-width: 300px; margin: 10px;">
@endforeach

Step 6: Define Routes

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

// routes/web.php
use App\Http\Controllers\ImageController;

Route::get('/images', [ImageController::class, 'index'])->name('image.index');
Route::get('/images/create', [ImageController::class, 'create'])->name('image.create');
Route::post('/images', [ImageController::class, 'store'])->name('image.store');

Step 7: Run the Application

Finally, run your Laravel development server:

php artisan serve

Visit http://127.0.0.1:8000/images in your browser to see the uploaded images and http://127.0.0.1:8000/images/create to upload new images.

That’s it! You’ve successfully implemented image upload functionality in Laravel.

Check our tools website Word count
Check our tools website check More tutorial

Leave a Reply