How to Upload and Display Images in Laravel Application?

How to Upload and Display Images in Laravel Application?

In this article, we are going to upload and display images in the Laravel Application. So let’s do it Step-by-Step:

Step 1: Install Laravel Application

There are lots of methods to create a fresh Laravel Project, but I going to create using composer.

$ composer create-project laravel/laravel econtact
$ cd econtact
$ php artisan serve

Step: 2 Database Configuration

Now we have to do some changes in .env like Database Name, Username, Password.

Step 3: Add Migration

php artisan make:migration create_contacts_table --create=contacts

Now, we need to add some code to the “database/migrations “

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('image');
            $table->string('phone');
            $table->string('email');
            $table->string('groups');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}

Step 4: Add Route

After migration, we need to set Resource Route to our Application. To do that add code in “routes/web.php”

Route::resource('contacts', ContactController::class);

Step 5: Add Controller and Model

We can create Controller and Model separately but in this post, we will going to create using a single command.

php artisan make:controller ContactController --resource --model=Contact

To apply logic in our Application we need to code in Controller so, let’s get started with the sample code given below to ContactController.php

<?php

namespace App\Http\Controllers;

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

class ContactController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $contacts = Contact::latest()->paginate(5);

        return view('contacts.index', compact('contacts'))
            ->with('i', (request()->input('page', 1) - 1) * 5);

        // $contacts = Contact::latest();
        // return view('contacts.index', compact('contacts'));
    }

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
        $request->validate([
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required',
            'groups' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

        ]);

        if ($image = $request->file('image')) {
            $imagePath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imagePath, $profileImage);
            $input['image'] = "$profileImage";
        }

        Contact::create($input);


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

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Contact  $contact
     * @return \Illuminate\Http\Response
     */
    public function show(Contact $contact)
    {
        return view('contacts.show', compact('contact'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Contact  $contact
     * @return \Illuminate\Http\Response
     */
    public function edit(Contact $contact)
    {
        return view('contacts.edit', compact('contact'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Contact  $contact
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Contact $contact)
    {
        $input = $request->all();
        $request->validate([
            'name' => 'required',
            'phone' => 'required',
            'email' => 'required',
            'groups' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',

        ]);

        if ($image = $request->file('image')) {
            $imagePath = 'image/';
            $profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imagePath, $profileImage);
            $input['image'] = "$profileImage";
        } else {
            unset($input['image']);
        }

        $contact->update($input);


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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Contact  $contact
     * @return \Illuminate\Http\Response
     */
    public function destroy(Contact $contact)
    {
        $contact->delete();

        return redirect()->route('contacts.index')
            ->with('success', 'Contact deleted successfully');
    }
}

Now add some code in “app/Models/Product.php” 

<?php

namespace App\Models;

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

class Contact extends Model
{
    use HasFactory;
    protected $fillable = [
        'name', 'phone', 'email', 'groups', 'image'
    ];
}

Step 6: Add Blade Files

Now, we need to add design for our Application so to do that, we need to add files in resources/views/contacts

Before that add bootstrap and other supportive files to your application in public/ other files like bootstrap, font awesome, etc.

1. layout.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url('bootstrap/css/bootstrap.min.css')}}">
    <link rel="stylesheet" href="{{ url('mdb5/css/mdb.min.css')}}">
    <link rel="stylesheet" href="{{ url('fonts/css/all.min.css')}}">
    <script src="{{ url('js/script.js') }}"></script>
    <title>Laravel 8 CRUD - Contact Application</title>
</head>

<body class="bg-muted">

    @yield('content')


    <script src="{{ url('bootstrap/js/bootstrap.min.js')}}"></script>
    <script src="{{ url('mdb5/js/mdb.min.js')}}"></script>
</body>

</html>

2. create.blade.php

@extends('contacts/layout')
@section('content')
<div class="container my-5">
    <div class="row px-4">
        <form action="{{ route('contacts.store') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row g-3 mb-3">
                <div class="col-4">
                    <label for="clientname" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" name="name" aria-describedby="name">
                </div>
                <div class="col-4">
                    <label for="image" class="form-label">Profile Image</label>
                    <input type="file" class="form-control" name="image" aria-describedby="image">
                </div>
                <div class="col-4">
                    <label for="phone" class="form-label">Phone</label>
                    <input type="text" class="form-control" id="phone" name="phone" aria-describedby="phone">
                </div>
                <div class="col-4">
                    <label for="group" class="form-label">Group</label>
                    <input type="text" class="form-control" id="groups" name="groups" aria-describedby="group">
                </div>
            </div>
            <div class="row g-3 mb-3">
                <div class="col-8 ">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" name="email" aria-describedby="email">
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>
@endsection

3. edit.blade.php

@extends('contacts/layout')
@section('content')
<div class="container my-5">
    <div class="row px-4">
        <form action="{{ route('contacts.update',$contact->id) }}" method="POST" enctype="multipart/form-data">
            @csrf
            @method('PUT')
            <div class="row g-3 mb-3">
                <div class="col-4">
                    <label for="clientname" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" name="name" value="{{ $contact->name }}" aria-describedby="name">
                </div>
                <div class="col-md-4">
                    <div class="form-group">
                        <strong>Profile Image:</strong>
                        <input type="file" name="image" class="form-control" placeholder="Profile Image">
                        <img src="/image/{{ $contact->image }}" width="300px">
                    </div>
                </div>
                <div class="col-4">
                    <label for="phone" class="form-label">Phone</label>
                    <input type="text" class="form-control" id="phone" name="phone" value="{{ $contact->phone }}" aria-describedby="phone">
                </div>
                <div class="col-4">
                    <label for="group" class="form-label">Group</label>
                    <input type="text" class="form-control" id="groups" name="groups" value="{{ $contact->groups }}" aria-describedby="group">
                </div>
            </div>
            <div class="row g-3 mb-3">
                <div class="col-8 ">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email" name="email" value="{{ $contact->email }}" aria-describedby="email">
                </div>
            </div>

            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>
@endsection

4. index.blade.php

   @extends('contacts/layout')
   @section('content')
   <!-- Content Row -->
   <div class="container my-5">
       <div class="heading d-flex justify-content-between my-5">
           <h1 class="h3 text-info fw-bold">Laravel 8 Application - eContact</h1>
           <a href="{{ route('contacts.create') }}" class="btn btn-outline-info"><i class="fas fa-plus"></i> Add Contact</a>
       </div>
       @if ($message = Session::get('success'))
       <div class="alert alert-success">
           <p>{{ $message }}</p>
       </div>
       @endif
       <div class="row">
           <table class="table">
               <thead>
                   <tr>
                       <th scope="col">#</th>
                       <th scope="col">Name</th>
                       <th scope="col">Profile Image</th>
                       <th scope="col">Phone</th>
                       <th scope="col">Email</th>
                       <th scope="col">Groups</th>
                   </tr>
               </thead>
               <tbody>
                   @foreach ($contacts as $contact)
                   <tr>
                       <th scope="row">{{ ++$i }}</th>
                       <td>{{ $contact->name }}</td>
                       <td><img src="/image/{{ $contact->image }}" width="100px"></td>
                       <td>{{ $contact->phone }}</td>
                       <td>{{ $contact->email }}</td>
                       <td>{{ $contact->groups }}</td>
                       <td>
                           <form action="{{ route('contacts.destroy',$contact->id) }}" method="POST">

                               <!-- <a class="btn btn-info" href="{{ route('contacts.show',$contact->id) }}">Show</a> -->

                               <a class="btn btn-primary" href="{{ route('contacts.edit',$contact->id) }}">Edit</a>

                               @csrf
                               @method('DELETE')

                               <button type="submit" class="btn btn-danger">Delete</button>
                           </form>
                       </td>
                   </tr>
                   @endforeach
               </tbody>
           </table>

       </div>
   </div>

   @endsection

Step 7: Screenshots




Copyright © 2020-2021 Engineer Jagat All rights reserved. Developed by Ravindra Rana