Home Laravel 9 Laravel 11 Image Upload Example

Laravel 11 Image Upload Example

12 min read
0
0
418

In this lesson we talk about laravel 11 image uploading and display the image step by step.Laravel is world famous php framework.it has various features.Laravel is a MVC architecture. In this tutorial will see how to make a Image Uploading and Display the image in Laravel 11. Here is the Best Place to Learn Laravel 11.

Install Laravel 11

Create  a new Project type  the command on the command prompt  . I create the project name image-example
Laravel 11 Tutorial  Setup the Project

composer create-project laravel/laravel img-app

Database setup

Create the Database on xampp which name is dboffice

After created the database.you have to give the and databasename and user creditinels on laravel .env file.

Create Migration and Create Model

php artisan make:model Product -m

Click and open the Migration file

inside the function up() function i shown in below clearly.

public function up(): void
  {
      Schema::create('products', function (Blueprint $table) {
          $table->id();

          $table->string('productname');
          $table->string('description');
          $table->double('price');
          $table->string('photo', 300)->nullable();
          $table->timestamps();
      });
  }

After add the lines type

php artisan migrate

After Model is Created the look like this. Code inside Model Class (app\Models\)

class Product extends Model
{
    protected $table = 'products';
    protected $primaryKey = 'id';
     protected $fillable = [
          'productname',
          'description',
          'price',
          'photo'
      ];

    use HasFactory;
}

Create Controller

Create the controller name which is ProductController 

php artisan make:controller productController --resource

inside the controller you have do the following code snippt

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
class productController extends Controller
{
    protected $products;

    public function __construct(){
        $this->products = new Product();
    }   
    public function index()
    {
        $products = $this->products->all();      
        return view('product.index', compact('products'));
    }

 
    public function create()
    {
       
    }


    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'productname' => 'required',
        
            'description' => 'required',
            'price' => 'required',
            'photo' => 'image|mimes:jpeg,png,jpg,gif|max:2048', // Adjust file size and allowed extensions as needed
        ]);

        // Check if the file was uploaded successfully
        if ($request->hasFile('photo')) {
            // Generate a unique file name
            $fileName = time().$request->file('photo')->getClientOriginalName();
            // Move the uploaded file to the public/images directory
            $request->file('photo')->move(public_path('images'), $fileName);
            // Save the product with the file name
            $validatedData['photo'] = $fileName; 
        }
        Product::create($validatedData);
        return redirect()->back();
    }

    
    public function show(string $id)
    {
       
    }

   
    public function edit(string $id)
    {
       
    }

    
    public function update(Request $request, string $id)
    {
        
    }

    
    public function destroy(string $id)
    {
        
    }
}

Create Views

Create a Folder inside the resources-views

inside the views folder create the product folder

In Laravel you have create the pages using layout.blade.php

Create page layout.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
            body,
            html {
                margin: 0;
                padding: 0;
                height: 100%;
            }

            .container1 {
                display: flex;
                height: 100%;
            }

            .sidebar {
                flex: 0 0 250px;
                background-color: #333;
                color: #fff;
            }

            .sidebar ul {
                list-style: none;
                padding: 0;
            }

            .sidebar ul li {
                padding: 10px;
            }

            .sidebar ul li a {
                color: #fff;
                text-decoration: none;
            }

            .sidebar ul li a:hover {
                background-color: #555;
            }

            .content {
                flex: 1;
                padding: 20px;
            }
        </style>


<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

</head>
<body>

<div class="container1">
            <nav class="sidebar">
                <ul>
                    <li><a href="#">Dashboard</a></li>
                    <li><a href="#">Category</a></li>
                    <li><a href="#">Products</a></li>
                    <li><a href="#">Logout</a></li>
                </ul>
            </nav>
            <main class="content">
                        @yield('content')
            </main>
        </div>
    </div>     



    
</body>
</html>

Create page inside the product folder

index.blade.php

@extends('layout')
@section('content')
    <div class="container">
        <h3 align="center" class="mt-5">Products</h3>
        <div class="row">
            <div class="col-md-2">
            </div>
            <div class="col-md-8">

            <div class="form-area">
                <form method="POST" action="{{ route('product.store') }}" enctype="multipart/form-data">
                    @csrf
                    <div class="row">
                        <div class="col-md-6">
                            <label>Product Name</label>
                            <input type="text" class="form-control" name="productname">
                        </div>
                      

                        <div class="col-md-6">
                            <label>Description</label>
                            <input type="text" class="form-control" name="description">
                        </div>

                        <div class="col-md-6">
                            <label>Price</label>
                            <input type="text" class="form-control" name="price">
                        </div>

              
                        <div class="col-md-6">
                            <label>Image</label>
                            <input class="form-control" name="photo" type="file" id="photo">
                        </div>


                    </div>
                    <div class="row">
                        <div class="col-md-12 mt-3">
                            <input type="submit" class="btn btn-primary" value="Register">
                        </div>
                    </div>
                </form>



            </div>


                <table class="table mt-5">
                    <thead>
                      <tr>
                        <th scope="col">#</th>
                        <th scope="col">Product Name</th>
                
                        <th scope="col">Price</th>
                        <th scope="col">Image</th>
               
                      </tr>
                    </thead>
                    <tbody>
                        @foreach ( $products as $key => $product )
                        <tr>
                            <td scope="col">{{ ++$key }}</td>
                            <td scope="col">{{ $product->productname }}</td>                            
                            <td scope="col">{{ $product->price }}</td>
                            <td scope="col">
                            @if ($product->photo)
                                    <img src="{{ asset('images/' . $product->photo) }}" alt="Product Image" width="100">
                                @else
                                    <img src="{{ asset('images/default.jpg') }}" alt="Default Image" width="100">
                                @endif
                            </td>
                          </tr>
                        @endforeach
                    </tbody>
                  </table>
            </div>
        </div>
    </div>
@endsection
@push('css')
    <style>
        .form-area{
            padding: 20px;
            margin-top: 20px;
            background-color: #FFFF00;
        }
        .bi-trash-fill{
            color:red;
            font-size: 18px;
        }
        .bi-pencil{
            color:green;
            font-size: 18px;
            margin-left: 20px;
        }
    </style>
@endpush

Routes

Pages are Manage through routes. If you are crud system simple you can add it the routes one line look like this

<?php

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

Route::get('/', function () {
    return view('welcome');
});
Route::resource('/product', ProductController::class);

 

 

 

    Load More Related Articles
    Load More By admin
    Load More In Laravel 9

    Leave a Reply

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

    Check Also

    How to Make a Admin Panel Using React MUI

    I have design the Admin Basic templete using React MUI Design Admin Dashboard and Login.He…