How to create CRUD with image in Laravel 5

Published Date: 25-Nov-2017 | Tags: Laravel 5.5  CRUD  Image Upload  

This tutorial I want to show you how to create a complete CRUD operations and image upload with Laravel 5.5 and bootstrap 4.

Suppose that your server is running on port 80 and your project folder is /demo.

Note

  • I use laravelcollective to create form. So please install laravelcollective if you not yet install it. You can visit here for the installation guide.
  • I use bootstrap 4 for my UI, so please check bootstrap if you are new to bootstrap.

 

Step 1: Create Database Table

 Create table Images with structure as below.

image table structure

 

Step 2: Database Configuration

Edit this file /demo/.env and update your database name, username and password.

Suppose that your database name is demo, username is root, and password is empty.

laravel db config

 

Step 3: Add Route

Add these lines to file /demo/routes/web.php.

Route::group(['prefix' => 'laravel-crud-image-gallery'], function () {
    Route::get('/', 'Crud4Controller@index');
    Route::match(['get', 'post'], 'create', 'Crud4Controller@create');
    Route::match(['get', 'put'], 'update/{id}', 'Crud4Controller@update');
    Route::delete('delete/{id}', 'Crud4Controller@delete');
});

 

Step 4: Create Model

Create model file Image.php in /demo/app.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{

}

 

Step 5: Create View

Create layout view file default.blade.php in /demo/resources/views/layout. (create folder layout if it does not exist) 

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">
@yield('head')
<!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    @yield('css')
</head>
<body style="padding-top: 100px;padding-bottom: 50px;background: whitesmoke">
<nav class="navbar fixed-top navbar-expand-sm navbar-dark bg-info">
    <a class="navbar-brand" target="_blank" href="http://www.codovel.com">CODOVEL.COM</a>
    @yield('nav')
</nav>
@yield('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
@yield('js')
</body>
</html>

 

Create view file index.blade.php in /demo/resources/views/crud_4. (create folder crud_4 if it does not exist)

@extends('layout.default')
@section('css')
    <style>
        a, a:hover {
            color: white;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="float-right">
            <a href="{{url('laravel-crud-image-gallery/create')}}" class="btn btn-primary">New</a>
        </div>
        <h1 style="font-size: 2.2rem">Image Gallery (Image CRUD Tutorial)</h1>
        <hr/>
        <div class="row">
            @foreach($images as $image)
                <div class="col-md-4 col-lg-3" style="margin-bottom: 20px">
                    <div class="card">
                        <img class="card-img-top"
                             src="{{url($image->image? 'uploads/'.$image->image:'images/noimage.jpg')}}"
                             alt="{{$image->description}}" width="100%" height="180px"/>
                        <div class="card-body">
                            <h6 class="card-title text-center">{{ucwords($image->description)}}</h6>
                        </div>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item">
                                <form id="frm_{{$image->id}}"
                                      action="{{url('laravel-crud-image-gallery/delete/'.$image->id)}}"
                                      method="post" style="padding-bottom: 0px;margin-bottom: 0px">
                                    <div class="row">
                                        <div class="col-sm-6">
                                            <a href="javascript:if(confirm('Are you sure want to delete?')) $('#frm_{{$image->id}}').submit()"
                                               class="btn btn-danger btn-sm btn-block">Delete</a>
                                        </div>
                                        <div class="col-sm-6">
                                            <a href="{{url('laravel-crud-image-gallery/update/'.$image->id)}}"
                                               class="btn btn-primary btn-sm btn-block">Edit</a>
                                        </div>
                                        <input type="hidden" name="_method" value="delete"/>
                                        {{csrf_field()}}
                                    </div>
                                </form>
                            </li>
                        </ul>
                    </div>
                </div>
            @endforeach
        </div>
         <nav>
            <ul class="pagination justify-content-end">
                {{$images->links('vendor.pagination.bootstrap-4')}}
            </ul>
        </nav>
    </div>
@endsection

Note: I use boostrap 4 pagination in the above view. So please export laravel built-in pagination files by going to terminal or command prompt (for window users), navigate to your project directory (/demo), and run this command

php artisan vendor:publish --tag=laravel-pagination

The above command will place all pagination views in the /resources/views/vendor/pagination. You can customize and use the one you need.

Create view file form.blade.php in /demo/resources/views/crud_4. (create folder crud_4 if it does not exist)

@extends('layout.default')
@section('css')
    <style>
        .form-group.required label:after {
            content: " *";
            color: red;
            font-weight: bold;
        }
    </style>
@endsection
@section('content')
    <div class="container">
        <div class="col-md-8 offset-md-2">
            <h1>{{isset($image)?'Edit':'New'}} Image</h1>
            <hr/>
            @if(isset($image))
                {!! Form::model($image,['method'=>'put','files'=>true]) !!}
            @else
                {!! Form::open(['files'=>true]) !!}
            @endif
            <div class="form-group row">
                {!! Form::label("image","Image",["class"=>"col-form-label col-md-3"]) !!}
                <div class="col-md-5">
                    <img id="preview"
                         src="{{asset((isset($image) && $image->image!='')?'uploads/'.$image->image:'images/noimage.jpg')}}"
                         height="200px" width="200px"/>
                    {!! Form::file("image",["class"=>"form-control","style"=>"display:none"]) !!}
                    <br/>
                    <a href="javascript:changeProfile();">Change</a> |
                    <a style="color: red" href="javascript:removeImage()">Remove</a>
                    <input type="hidden" style="display: none" value="0" name="remove" id="remove">
                </div>
            </div>
            <div class="form-group row required">
                {!! Form::label("description","Description",["class"=>"col-form-label col-md-3 col-lg-2"]) !!}
                <div class="col-md-8">
                    {!! Form::text("description",null,["class"=>"form-control".($errors->has('description')?" is-invalid":""),"autofocus",'placeholder'=>'Description']) !!}
                    {!! $errors->first('description','<span class="invalid-feedback">:message</span>') !!}
                </div>
            </div>
            <div class="form-group row">
                <div class="col-md-3 col-lg-2"></div>
                <div class="col-md-4">
                    <a href="{{url('laravel-crud-image-gallery')}}" class="btn btn-danger">
                        Back</a>
                    {!! Form::button("Save",["type" => "submit","class"=>"btn
                btn-primary"])!!}
                </div>
            </div>
            {!! Form::close() !!}
        </div>
    </div>
@endsection
@section('js')
    <script>
        function changeProfile() {
            $('#image').click();
        }
        $('#image').change(function () {
            var imgPath = $(this)[0].value;
            var ext = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
            if (ext == "gif" || ext == "png" || ext == "jpg" || ext == "jpeg")
                readURL(this);
            else
                alert("Please select image file (jpg, jpeg, png).")
        });
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.readAsDataURL(input.files[0]);
                reader.onload = function (e) {
                    $('#preview').attr('src', e.target.result);
                    $('#remove').val(0);
                }
            }
        }
        function removeImage() {
            $('#preview').attr('src', '{{url('images/noimage.jpg')}}');
            $('#remove').val(1);
        }
    </script>
@endsection

 

Step 6: Create Controller

Create controller file Crud4Controller in /demo/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

use App\Customer;
use App\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class Crud4Controller extends Controller
{
    public function index(Request $request)
    {
        $images = Image::orderBy('created_at', 'desc')->paginate(8);
        return view('crud_4.index', compact('images'));
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
            return view('crud_4.form');
        else {
            $rules = [
                'description' => 'required',
            ];
            $this->validate($request, $rules);
            $image = new Image();
            if ($request->hasFile('image')) {
                $dir = 'uploads/';
                $extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
                $fileName = str_random() . '.' . $extension; // rename image
                $request->file('image')->move($dir, $fileName);
                $image->image = $fileName;
            }
            $image->description = $request->description;
            $image->save();
            return redirect('/laravel-crud-image-gallery');
        }
    }

    public function delete($id)
    {
        Image::destroy($id);
        return redirect('/laravel-crud-image-gallery');
    }

    public function update(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('crud_4.form', ['image' => Image::find($id)]);
        else {
            $rules = [
                'description' => 'required',
            ];
            $this->validate($request, $rules);
            $image = Image::find($id);
            if ($request->hasFile('image')) {
                $dir = 'uploads/';
                if ($image->image != '' && File::exists($dir . $image->image))
                    File::delete($dir . $image->image);
                $extension = strtolower($request->file('image')->getClientOriginalExtension());
                $fileName = str_random() . '.' . $extension;
                $request->file('image')->move($dir, $fileName);
                $image->image = $fileName;
            } elseif ($request->remove == 1 && File::exists('uploads/' . $image->image)) {
                File::delete('uploads/' . $image->post_image);
                $image->image = null;
            }
            $image->description = $request->description;
            $image->save();
            return redirect('/laravel-crud-image-gallery');
        }
    }
}

 

Step 7: Test

Open your browser and type http://localhost/demo/public/laravel-crud-image-gallery. Then you will see it.

laravel 5.5 CRUD image gallery

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.