Restaurant Management System ( Part 9 )

Published Date: 17-Jan-2018 | Tags: Laravel 5.5  Bootstrap 3  Project  

This tutorial I want to show you how to manage Product in Admin.

Note: I recommend you to check all pervious tutorials before coming to this step. Because some tutorials have relationship with others..

 

Step 1: Create Model

Create model Product.php in /demo/app.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function product_category()
    {
        return $this->belongsTo('App\ProductCategory');
    }

    public function recipes()
    {
        return $this->hasMany('App\Recipe');
    }
}

 

Step 2: Create View

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

<h1 class="page-header">Product
    <div class="pull-right">
        <a href="javascript:ajaxLoad('product/create')" class="btn btn-primary"><i
                    class="glyphicon glyphicon-plus-sign"></i> New</a>
        <a href="{{url('product/print')}}" target="_blank" class="btn btn-success"><i
                    class="glyphicon glyphicon-print"></i> Print</a>
    </div>
</h1>
<div class="col-md-3 form-group">
    {!! Form::select('category',['-1'=>'All Categories']+App\ProductCategory::orderBy('name')->pluck('name','id')->toArray() ,Session::get('product_category'),['class'=>'form-control','style'=>'height:40px','onChange'=>'ajaxLoad("'.url("product").'?category="+this.value)']) !!}
</div>
<div class="col-sm-4 form-group">
    <div class="input-group">
        <input class="form-control" id="search" value="{{ Session::get('product_search') }}"
               onkeydown="if (event.keyCode == 13) ajaxLoad('{{url('product')}}?ok=1&search='+this.value)"
               placeholder="Search..."
               type="text">

        <div class="input-group-btn">
            <button type="button" class="btn btn-default"
                    onclick="ajaxLoad('{{url('product')}}?ok=1&search='+$('#search').val())"><i
                        class="glyphicon glyphicon-search"></i>
            </button>
        </div>
    </div>
</div>
<table class="table table-bordered table-striped">
    <thead>
    <tr>
        <th class="hidden-xs hidden-sm" style="text-align: center">Picture</th>
        <th width="80px" style="text-align: center">
            <a href="javascript:ajaxLoad('product?field=id&sort={{Session::get("product_sort")=="asc"?"desc":"asc"}}')">
                Code
            </a>
            <i style="font-size: 12px"
               class="glyphicon  {{ Session::get('product_field')=='id'?(Session::get('product_sort')=='asc'?'glyphicon-sort-by-alphabet':'glyphicon-sort-by-alphabet-alt'):'' }}">
            </i>
        </th>
        <th>
            <a href="javascript:ajaxLoad('product?field=name&sort={{Session::get("product_sort")=="asc"?"desc":"asc"}}')">
                Name
            </a>
            <i style="font-size: 12px"
               class="glyphicon  {{ Session::get('product_field')=='name'?(Session::get('product_sort')=='asc'?'glyphicon-sort-by-alphabet':'glyphicon-sort-by-alphabet-alt'):'' }}">
            </i>
        </th>
        <th class="hidden-xs hidden-sm">Category</th>
        <th style="text-align: right">Unitprice</th>
        <th width="140px"></th>
    </tr>
    </thead>
    <tbody>
    <?php $i = 1;?>
    @foreach($products as $key=>$product)
        <tr>
            <td class="hidden-xs hidden-sm" style="text-align: center">
                <img src="{{$product->image!='' && File::exists('images/products/'.$product->image)?'/images/products/'.$product->image:'/images/default.jpg'}}"
                     width="80px" height="70px"/>
            </td>
            <td align="center" style="vertical-align: middle">{{$product->id}}</td>
            <td style="vertical-align: middle">{{$product->name}}</td>
            <td class="hidden-xs hidden-sm"
                style="vertical-align: middle">{{$product->product_category?$product->product_category->name:''}}</td>
            <td align="right" style="vertical-align: middle">$ {{$product->unitprice}}</td>
            <td style="text-align: center;vertical-align: middle">
                <a class="btn btn-primary btn-xs" title="Edit"
                   href="javascript:ajaxLoad('product/update/{{$product->id}}')">
                    <i class="glyphicon glyphicon-edit"></i> Edit</a>
                <a class="btn btn-danger btn-xs" title="Delete"
                   href="javascript:if(confirm('Are you sure want to delete?')) ajaxDelete('product/delete/{{$product->id}}','{{csrf_token()}}')">
                    <i class="glyphicon glyphicon-trash"></i> Delete
                </a>
            </td>
        </tr>
    @endforeach
    </tbody>
</table>
<div class="pull-right">{!! str_replace('/?','?',$products->render()) !!}</div>
<div class="row">
    <i class="col-sm-12">
        Total: {{$products->total()}} records
    </i>
</div>

 

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

<h2 class="page-header">{{isset($product)?'Edit':'New'}} Product</h2>
@if(isset($product))
    {!! Form::model($product,["id"=>"frm","class"=>"form-horizontal","method"=>"put"]) !!}
@else
    {!! Form::open(["id"=>"frm","class"=>"form-horizontal"]) !!}
@endif
<div class="form-group" id="form-image-error">
    {!! Form::label("image","Image",["class"=>"control-label col-md-2"]) !!}
    <div class="col-md-5">
        <img id="preview"
             src="{{(isset($product) && $product->image!='' && File::exists('images/products/'.$product->image))?'/images/products/'.$product->image:'/images/default.jpg'}}"
             onerror="this.src='/images/default.jpg'" width="150px" height="130px"
             style="padding: 5px"/>
        {!! Form::file("image",["class"=>"form-control","style"=>"display:none","id"=>"image"]) !!}
        <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">
        <span id="image-error" class="help-block"></span>
    </div>
</div>
<div class="form-group required" id="form-name-error">
    {!! Form::label("name","Name",["class"=>"control-label col-md-2"]) !!}
    <div class="col-md-5">
        {!! Form::text("name",null,["class"=>"form-control required","id"=>"focus"]) !!}
        <span id="name-error" class="help-block"></span>
    </div>
</div>
<div class="form-group">
    {!! Form::label("product_category_id","Category",["class"=>"control-label col-md-2"]) !!}
    <div class="col-md-5">
        {!! Form::select("product_category_id",\App\ProductCategory::orderBy('name')->pluck('name','id'),null,["class"=>"form-control","style"=>"height:40px"]) !!}
    </div>
</div>
<div class="form-group required" id="form-unitprice-error">
    {!! Form::label("unitprice","Unitprice",["class"=>"control-label col-md-2"]) !!}
    <div class="col-md-5">
        {!! Form::text("unitprice",null,["class"=>"form-control required"]) !!}
        <span id="unitprice-error" class="help-block"></span>
    </div>
</div>
<div class="form-group">
    <div class="col-md-5 col-md-push-2">
        <a href="javascript:ajaxLoad('product')" class="btn btn-danger"><i class="glyphicon glyphicon-backward"></i>
            Back</a>
        {!! Form::button("<i class='glyphicon glyphicon-floppy-disk'></i> Save",["type" => "submit","class"=>"btn
    btn-primary","id"=>"btn_save"])!!}
    </div>
</div>
{!! Form::close() !!}
<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.onload = function (e) {
                $('#preview').attr('src', e.target.result);
                $("#remove").val(0);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
    function removeImage() {
        $('#preview').attr('src', '/images/default.jpg');
        $("#remove").val(1);
    }
</script>

 

Create view print.blade.php in /resources/views/product. (create folder product if it does not exist)

<link href="{{ asset('bootstrap-3.3.7/css/bootstrap.min.css') }}" rel="stylesheet">
<div class="container-fluid">
    <h1 class="page-header">Product List </h1>
    <table class="table table-bordered">
        <thead>
        <tr>
            <th width="80px" style="text-align: center"> Code</th>
            <th> Name</th>
            <th style="text-align: right">Unitprice</th>
        </tr>
        </thead>
        <tbody>
        @foreach($categories as $key=>$category)
            <tr style="background: whitesmoke">
                <th colspan="3">{{$category->name}}</th>
            </tr>
            @foreach($category->products as $product)
                <tr>
                    <td align="center">{{$product->id}}</td>
                    <td>{{$product->name}}</td>
                    <td align="right">$ {{$product->unitprice}}</td>
                </tr>
            @endforeach
        @endforeach
        </tbody>
    </table>
</div>

 

Step 3: Create Controller

Create controller ProductController.php in /demo/app/Http/Cotrollers.

<?php
namespace App\Http\Controllers;

use App\Lib\ResizeImageFile;
use App\Product;
use App\ProductCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class ProductController extends Controller
{
    public function index()
    {
        Session::put('product_search', Input::has('ok') ? Input::get('search') : (Session::has('product_search') ? Session::get('product_search') : ''));
        Session::put('product_category', Input::has('category') ? Input::get('category') : (Session::has('product_category') ? Session::get('product_category') : -1));
        Session::put('product_field', Input::has('field') ? Input::get('field') : (Session::has('product_field') ? Session::get('product_field') : 'name'));
        Session::put('product_sort', Input::has('sort') ? Input::get('sort') : (Session::has('product_sort') ? Session::get('product_sort') : 'asc'));
        $products = new Product();
        if (Session::get('product_category') != -1)
            $products = $products->where('product_category_id', Session::get('product_category'));
        $products = $products->where('name', 'like', '%' . Session::get('product_search') . '%')
            ->orderBy(Session::get('product_field'), Session::get('product_sort'))->paginate(10);
        return view('product.index', ['products' => $products]);
    }

    public function printProducts()
    {
        if (Session::get('product_category') != -1)
            $categories = ProductCategory::find(Session::get('product_category'));
        else
            $categories = ProductCategory::orderBy('name')->get();
        return view('product.print', ['categories' => $categories]);
    }

    public function update(Request $request, $id)
    {
        if ($request->isMethod('get'))
            return view('product.form', ['product' => Product::find($id)]);
        else {
            $product = Product::find($id);
            $rules = ["unitprice" => "required|numeric"];
            if ($product->name != Input::get('name'))
                $rules += ['name' => 'required|unique:products'];
            $validator = Validator::make(Input::all(), $rules);
            if ($validator->fails()) {
                return array(
                    'fail' => true,
                    'errors' => $validator->getMessageBag()->toArray()
                );
            }
            $product->name = Input::get('name');
            $product->product_category_id = Input::get('product_category_id');
            $product->product_type_id = Input::get('product_type_id');
            $product->unitprice = Input::get('unitprice');
            $product->user_id = Auth::user()->id;
            if (Input::hasFile('image')) {
                if ($product->image != '')
                    File::delete('/images/products/' . $product->image);
                $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
                $dir = 'images/products/';
                $fileName = str_random() . '.' . $extension; // renameing image
                Input::file('image')->move($dir, $fileName);
                $resize = new ResizeImageFile($dir . $fileName);
                $resize->resizeImage(150, 130, 'exact');
                $resize->saveImage($dir . $fileName, 100);
                $product->image = $fileName;
            }
            if (Input::get('remove') == 1) {
                File::delete('/images/products/' . $product->image);
                $product->image = null;
            }
            $product->save();
            Session::put('msg_status', true);
        }
    }

    public function create(Request $request)
    {
        if ($request->isMethod('get'))
            return view('product.form');
        else {
            $validator = Validator::make(Input::all(), [
                "name" => "required|unique:products",
                "unitprice" => "required|numeric"
            ]);
            if ($validator->fails()) {
                return array(
                    'fail' => true,
                    'errors' => $validator->getMessageBag()->toArray()
                );
            }
            $product = new Product();
            $product->name = Input::get('name');
            $product->product_category_id = Input::get('product_category_id');
            $product->product_type_id = Input::get('product_type_id');
            $product->unitprice = Input::get('unitprice');
            $product->user_id = Auth::user()->id;
            if (Input::hasFile('image')) {
                $extension = Input::file('image')->getClientOriginalExtension(); // getting image extension
                $dir = 'images/products/';
                $fileName = str_random() . '.' . $extension; // renameing image
                Input::file('image')->move($dir, $fileName);
                $resize = new ResizeImageFile($dir . $fileName);
                $resize->resizeImage(150, 130, 'exact');
                $resize->saveImage($dir . $fileName, 100);
                $product->image = $fileName;
            }
            if (Input::get('remove') == 1) {
                File::delete('/images/products/' . $product->image);
                $product->image = null;
            }
            $product->save();
            Session::put('msg_status', true);
        }
    }

    public function delete($id)
    {
        $product = Product::find($id);
        File::delete('/images/products/' . $product->image);
        $product->delete();
        return redirect('product');
    }
}

 

Step 4: How to Test?

After login to admin screen, you will be able to access Product List option on the left side menu.

Note: You have to finish this tutorial restaurant-management-system-step-by-step-tutorial-part-10.html first before you can run this section without error. Because it has relationship with each other.

product-list

Hope you can do it.


Demo


Related Posts

© 2018 All Rights Reserved.