codovel

We no longer support this blog. Please visit this site instead. https://laravelprojectlab.com

Sunday, June 19, 2016

Complete laravel ajax CRUD, search, sort and pagination

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Create table products in MySQL database


or you can download sample data from here.

Step 2: Connect your Laravel project to MySQL database.Go to edit this file C:\wamp\www\test_laravel\.env and update your database information


Step 3: Create model file Product.php in C:\wamp\www\test_laravel\app

Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{

}

Step 4: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('product', 'ProductController');

Step 5: Create some view files index.blade.php, list.blade.php, create.blade.php, update.blade.php, _form.blade.php in C:\wamp\www\test_laravel\resources\views\product (please create product folder if not exist)

index.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">
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<style>
    .loading {
        background: lightgoldenrodyellow url('{{asset('images/processing.gif')}}') no-repeat center 65%;
        height: 80px;
        width: 100px;
        position: fixed;
        border-radius: 4px;
        left: 50%;
        top: 50%;
        margin: -40px 0 0 -50px;
        z-index: 2000;
        display: none;
    }
</style>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
            <div id="content"></div>
        </div>
        <div class="col-md-3"></div>
    </div>
    <div class="loading"></div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    function ajaxLoad(filename, content) {
        content = typeof content !== 'undefined' ? content : 'content';
        $('.loading').show();
        $.ajax({
            type: "GET",
            url: filename,
            contentType: false,
            success: function (data) {
                $("#" + content).html(data);
                $('.loading').hide();
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
    $(document).ready(function () {
        ajaxLoad('product/list');
    });
</script>
</body>
</html>

list.blade.php
<h1 class="page-header">Product List
    <div class="pull-right">
        <a href="javascript:ajaxLoad('product/create')" class="btn btn-primary pull-right"><i
                    class="glyphicon glyphicon-plus-sign"></i> New</a>
    </div>
</h1>
<div class="col-sm-7 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/list')}}?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/list')}}?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 width="50px" style="text-align: center">No</th>
        <th>
            <a href="javascript:ajaxLoad('product/list?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>
            <a href="javascript:ajaxLoad('product/list?field=unitprice&sort={{Session::get("product_sort")=="asc"?"desc":"asc"}}')">
                Unitprice
            </a>
            <i style="font-size: 12px"
               class="glyphicon  {{ Session::get('product_field')=='unitprice'?(Session::get('product_sort')=='asc'?'glyphicon-sort-by-alphabet':'glyphicon-sort-by-alphabet-alt'):'' }}">
            </i>
        </th>
        <th width="140px"></th>
    </tr>
    </thead>
    <tbody>
    <?php $i = 1;?>
    @foreach($products as $key=>$product)
        <tr>
            <td align="center">{{$i++}}</td>
            <td>{{$product->name}}</td>
            <td align="right">$ {{$product->unitprice}}</td>
            <td style="text-align: center">
                <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?')) ajaxLoad('product/delete/{{$product->id}}')">
                    <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>
<script>
    $('.pagination a').on('click', function (event) {
        event.preventDefault();
        ajaxLoad($(this).attr('href'));
    });
</script>

create.blade.php
<h2 class="page-header">New Product</h2>
{!! Form::open(["id"=>"frm","class"=>"form-horizontal"]) !!}
@include("product._form")
{!! Form::close() !!}


update.blade.php
<h2 class="page-header">Edit Product</h2>
{!! Form::model($product,["id"=>"frm","class"=>"form-horizontal"]) !!}
@include("product._form")
{!! Form::close() !!}


_form.blade.php
<div class="form-group required" id="form-name-error">
    {!! Form::label("name","Name",["class"=>"control-label col-md-3"]) !!}
    <div class="col-md-6">
        {!! Form::text("name",null,["class"=>"form-control required","id"=>"focus"]) !!}
        <span id="name-error" class="help-block"></span>
    </div>
</div>
<div class="form-group required" id="form-unitprice-error">
    {!! Form::label("unitprice","Unitprice",["class"=>"control-label col-md-3"]) !!}
    <div class="col-md-6">
        {!! 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-6 col-md-push-3">
        <a href="javascript:ajaxLoad('product/list')" 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"])!!}
    </div>
</div>
<script>
    $("#frm").submit(function (event) {
        event.preventDefault();
        $('.loading').show();
        var form = $(this);
        var data = new FormData($(this)[0]);
        var url = form.attr("action");
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#frm input.required, #frm textarea.required').each(function () {
                        index = $(this).attr('name');
                        if (index in data.errors) {
                            $("#form-" + index + "-error").addClass("has-error");
                            $("#" + index + "-error").html(data.errors[index]);
                        }
                        else {
                            $("#form-" + index + "-error").removeClass("has-error");
                            $("#" + index + "-error").empty();
                        }
                    });
                    $('#focus').focus().select();
                } else {
                    $(".has-error").removeClass("has-error");
                    $(".help-block").empty();
                    $('.loading').hide();
                    ajaxLoad(data.url, data.content);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
        return false;
    });
</script>

Step 6: Create controller file ProductController.php in here C:\wamp\www\test_laravel\app\Http\Controllers 
<?php
namespace App\Http\Controllers;

use App\Product;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;

class ProductController extends Controller
{
    public function getIndex()
    {
        return view('product.index');
    }

    public function getList()
    {
        Session::put('product_search', Input::has('ok') ? Input::get('search') : (Session::has('product_search') ? Session::get('product_search') : ''));
        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 = Product::where('name', 'like', '%' . Session::get('product_search') . '%')
            ->orderBy(Session::get('product_field'), Session::get('product_sort'))->paginate(8);
        return view('product.list', ['products' => $products]);
    }

    public function getUpdate($id)
    {
        return view('product.update', ['product' => Product::find($id)]);
    }

    public function postUpdate($id)
    {
        $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->unitprice = Input::get('unitprice');
        $product->save();
        return ['url' => 'product/list'];
    }

    public function getCreate()
    {
        return view('product.create');
    }

    public function postCreate()
    {
        $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->unitprice = Input::get('unitprice');
        $product->save();
        return ['url' => 'product/list'];
    }

    public function getDelete($id)
    {
        Product::destroy($id);
        return Redirect('product/list');
    }

}

How to test? open your browser and type http://localhost/test_laravel/public/product. You will see this screen


Saturday, June 18, 2016

Laravel resize image file when upload with ajax loading

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 2: Create view file resize_upload_image_file.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="_token" content="{{ csrf_token() }}"/>
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <center>
                <br/>

                <div style="width:200px;height: 200px;border: 1px solid whitesmoke;text-align: center" id="img1">
                    <img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>
                </div>
                <br/>

                <p>
                    <a href="javascript:changeProfile()" style="text-decoration: none;"><i
                                class="glyphicon glyphicon-edit"></i> Change</a>&nbsp;&nbsp;
                    <a href="javascript:removeFile()"
                       style="color: red;text-decoration: none;"><i
                                class="glyphicon glyphicon-trash"></i>
                        Remove</a>
                </p>
                <input type="file" id="file1" style="display: none"/>
            </center>
        </div>
        <div class="col-md-4"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    var filename = '';
    function changeProfile() {
        $('#file1').click();
    }
    $('#file1').change(function () {
        if ($(this).val() != '') {
            upload();

        }
    });
    function upload() {
        var file_data = $('#file1').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
        });
        $('#img1').html('<img src="{{asset('images/loader.gif')}}" style="padding-top: 40%"/>');
        $.ajax({
            url: "{{url('tutorial/resize-upload-image-file')}}", // point to server-side PHP script
            data: form_data,
            type: 'POST',
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                    alert(data.errors['file']);
                }
                else {
                    filename = data;
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('uploads')}}/' + data + '"/>');
                }
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
            }
        });
    }
    function removeFile() {
        if (filename != '')
            if (confirm('Are you sure want to remove profile picture?'))
                $.ajax({
                    url: "{{url('tutorial/remove-image-file')}}/" + filename, // point to server-side PHP script
                    type: 'GET',
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData: false,
                    success: function (data) {
                        $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                        filename = '';
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
    }
</script>
</body>
</html>

Step 3: Create controller file TutorialController.php in C:\wamp\www\test_laravel\app\Http\Controllers
<?php
namespace App\Http\Controllers;

use App\Lib\ResizeImageFile;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;

class TutorialController extends Controller
{
    public function getResizeUploadImageFile()
    {
        return view('tutorial.resize_upload_image_file');
    }

    public function postResizeUploadImageFile(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'file' => 'image',
            ],
            [
                'file.image' => 'The file must be an image (jpeg, png, bmp, gif, or svg)'
            ]);
        if ($validator->fails())
            return array(
                'fail' => true,
                'errors' => $validator->getMessageBag()->toArray()
            );
        $extension = $request->file('file')->getClientOriginalExtension(); // getting image extension
        $dir = 'uploads/';
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $request->file('file')->move($dir, $filename);
        $resize = new ResizeImageFile($dir . $filename);
        $resize->resizeImage(200, 200, 'exact');     // You can play around with these options(exact, portrait, landscape, auto, crop)
        $resize->saveImage($dir . $filename, 75);   // 75 is image quality (0-100)
        return $filename;
    }

    public function getRemoveImageFile($filename)
    {
        File::delete('uploads/' . $filename);
    }
}

How to test? open your browser and type http://localhost/test_laravel/public/tutorial/resize-upload-image-file. You will see this screen
 

Laravel upload image file with ajax loading

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 2: Create view file upload_image_profile.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="_token" content="{{ csrf_token() }}"/>
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-4"></div>
        <div class="col-md-4">
            <center>
                <br/>

                <div style="width:200px;height: 200px;border: 1px solid whitesmoke;text-align: center" id="img1">
                    <img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>
                </div>
                <br/>

                <p>
                    <a href="javascript:changeProfile()" style="text-decoration: none;"><i
                                class="glyphicon glyphicon-edit"></i> Change</a>&nbsp;&nbsp;
                    <a href="javascript:removeFile()"
                       style="color: red;text-decoration: none;"><i
                                class="glyphicon glyphicon-trash"></i>
                        Remove</a>
                </p>
                <input type="file" id="file1" style="display: none"/>
            </center>
        </div>
        <div class="col-md-4"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    var filename = '';
    function changeProfile() {
        $('#file1').click();
    }
    $('#file1').change(function () {
        if ($(this).val() != '') {
            upload();

        }
    });
    function upload() {
        var file_data = $('#file1').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        $.ajaxSetup({
            headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
        });
        $('#img1').html('<img src="{{asset('images/loader.gif')}}" style="padding-top: 40%"/>');
        $.ajax({
            url: "{{url('tutorial/upload-image-file')}}", // point to server-side PHP script
            data: form_data,
            type: 'POST',
            contentType: false,       // The content type used when sending data to the server.
            cache: false,             // To unable request pages to be cached
            processData: false,
            success: function (data) {
                if (data.fail) {
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                    alert(data.errors['file']);
                }
                else {
                    filename = data;
                    $('#img1').html('<img width="100%" height="100%" src="{{asset('uploads')}}/' + data + '"/>');
                }
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
                $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
            }
        });
    }
    function removeFile() {
        if (filename != '')
            if (confirm('Are you sure want to remove profile picture?'))
                $.ajax({
                    url: "{{url('tutorial/remove-image-file')}}/" + filename, // point to server-side PHP script
                    type: 'GET',
                    contentType: false,       // The content type used when sending data to the server.
                    cache: false,             // To unable request pages to be cached
                    processData: false,
                    success: function (data) {
                        $('#img1').html('<img width="100%" height="100%" src="{{asset('images/default.jpg')}}"/>');
                        filename = '';
                    },
                    error: function (xhr, status, error) {
                        alert(xhr.responseText);
                    }
                });
    }
</script>
</body>
</html>


Step 3: Create controller file TutorialController.php in here C:\wamp\www\test_laravel\app\Http\Controllers
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;

class TutorialController extends Controller
{
    public function getUploadImageFile()
    {
        return view('tutorial.upload_image_file');
    }
    public function postUploadImageFile(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'file' => 'image',
            ],
            [
                'file.image' => 'The file must be an image (jpeg, png, bmp, gif, or svg)'
            ]);
        if ($validator->fails())
            return array(
                'fail' => true,
                'errors' => $validator->getMessageBag()->toArray()
            );
        $extension = $request->file('file')->getClientOriginalExtension(); // getting image extension
        $dir = 'uploads/';
        $filename = uniqid() . '_' . time() . '.' . $extension;
        $request->file('file')->move($dir, $filename);
        return $filename;
    }

    public function getRemoveImageFile($filename)
    {
        File::delete('uploads/' . $filename);
    }
}


How to test? open your browser and type http://localhost/test_laravel/public/tutorial/upload-image-file. You will see this screen
 

Laravel show items base on its category in dropdownlist

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Create 2 tables in MySQL database, item_categories, and items

item_categories

items

or you can download sample data from here.

Step 2: Connect your Laravel project to MySQL database.Go to edit this file C:\wamp\www\test_laravel\.env and update your database information


Step 3: Create 2 model files Item.php and ItemCategory.php in C:\wamp\www\test_laravel\app

Item.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

}

ItemCategory.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ItemCategory extends Model
{
    public function items()
    {
        return $this->hasMany('App\Item');
    }
}

Step 4: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 5: Create view file item_base_on_category.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)
<!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">
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
            <h2 class="page-header">Form Example</h2>
            {!! Form::open(["id"=>"frm","class"=>"form-horizontal"]) !!}
            <div class="form-group">
                {!! Form::label("item_category_id","Item Category",["class"=>"control-label col-md-3"]) !!}
                <div class="col-md-8">
                    {!! Form::select("item_category_id",\App\ItemCategory::orderBy('name')->lists('name','id'),null,["class"=>"form-control required","id"=>"category","style"=>"height:auto"]) !!}
                </div>
            </div>
            <div class="form-group">
                {!! Form::label("item_id","Item",["class"=>"control-label col-md-3"]) !!}
                <div class="col-md-8">
                    {!! Form::select("item_id",[],null,["class"=>"form-control required","id"=>"item","style"=>"height:auto"]) !!}
                </div>
            </div>
            {!! Form::close() !!}
        </div>
        <div class="col-md-3"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    $('#category').on('change', function () {
        getItems($(this).val());
    });
    function getItems(category_id) {
        $.get("{{url('tutorial/items')}}/" + category_id, function (data) {
            $("#item").html(data);
        });
    }
    $(document).ready(function () {
        getItems($('#category').val());
    });
</script>
</body>
</html>


Step 6: Create controller file TutorialController.php in here C:\wamp\www\test_laravel\app\Http\Controllers
<?php
namespace App\Http\Controllers;
use App\ItemCategory;

class TutorialController extends Controller
{
    public function getItemBaseOnCategory()
    {
        return view('tutorial.item_base_on_category');
    }

    public function getItems($item_category)
    {
        $items = ItemCategory::find($item_category)->items()->orderBy('name')->lists('name', 'id');
        $list = '';
        foreach ($items as $key => $value) {
            $list .= "<option value='" . $key . "'>" . $value . "</option>";
        }
        return $list;
    }
}

How to test? open your browser and type http://localhost/test_laravel/public/tutorial/item-base-on-category. You will see this screen
 

Laravel bootstrap ajax menu navigation with loading animation

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)

Step 1: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 2: Create view file navbar.blade.php, view1.blade.php, view2.blade.php, and view3.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)

navbar.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">
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<style>
    .loading {
        background: lightgoldenrodyellow url('{{asset('images/processing.gif')}}') no-repeat center 65%;
        height: 80px;
        width: 100px;
        position: fixed;
        border-radius: 4px;
        left: 50%;
        top: 50%;
        margin: -40px 0 0 -50px;
        z-index: 2000;
        display: none;
    }
</style>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
            <nav class="navbar navbar-default">
                <div class="container-fluid">
                    <!-- Brand and toggle get grouped for better mobile display -->
                    <div class="navbar-header">
                        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                                data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                        <a class="navbar-brand" href="#">Header</a>
                    </div>
                    <!-- Collect the nav links, forms, and other content for toggling -->
                    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                        <ul class="nav navbar-nav navbar-right">
                            <li><a href="javascript:ajaxLoad('{{url('tutorial/view1')}}')">View 1</a></li>
                            <li><a href="javascript:ajaxLoad('{{url('tutorial/view2')}}')">View 2</a></li>
                            <li><a href="javascript:ajaxLoad('{{url('tutorial/view3')}}')">View 3</a></li>
                        </ul>
                    </div>
                    <!-- /.navbar-collapse -->
                </div>
                <!-- /.container-fluid -->
            </nav>
            <div id="content">click any menu above to change content here</div>
            <div class="loading"></div>
        </div>
        <div class="col-md-3"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
<script>
    function ajaxLoad(filename, content) {
        content = typeof content !== 'undefined' ? content : 'content';
        $('.loading').show();
        $.ajax({
            type: "GET",
            url: filename,
            contentType: false,
            success: function (data) {
                $("#" + content).html(data);
                $('.loading').hide();
            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
            }
        });
    }
</script>
</body>
</html>

view1.blade.php
<h1>View 1</h1>

view2.blade.php
<h1>View 2</h1>

view3.blade.php
<h1>View 3</h1>

Step 3: Create controller file TutorialController.php in here C:\wamp\www\test_laravel\app\Http\Controllers
<?php
namespace App\Http\Controllers;

class TutorialController extends Controller
{
    public function getNavbar()
    {
        return view('tutorial.navbar');
    }

    public function getView1()
    {
        return view('tutorial.view1');
    }

    public function getView2()
    {
        return view('tutorial.view2');
    }

    public function getView3()
    {
        return view('tutorial.view3');
    }
}

How to test? open your browser and type http://localhost/test_laravel/public/tutorial/navbar. You will see this screen

 

Laravel how to send email

Suppose that your project root folder is here C:\wamp\www\test_laravel.

Please download this file public.rar and extract to your public folder (C:\wamp\www\test_laravel\public)


Step 1: Configure email setting.Go to edit this file C:\wamp\www\test_laravel\.env and update your email information.


Step 2: Go to edit this file C:\wamp\www\test_laravel\config\mail.php and update your sender information


Step 3: Edit route file (C:\wamp\www\test_laravel\app\Http\routes.php) and add
Route::controller('tutorial', 'TutorialController');

Step 4: Create 2 view files send_email.blade.php and mail_body.blade.php in C:\wamp\www\test_laravel\resources\views\tutorial (please create tutorial folder if not exist)

send_email.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">
    <title>Laravel Tutorials</title>
    <!-- Styles -->
    <link href="{{ asset('bootstrap-3.3.6/css/bootstrap.min.css') }}" rel="stylesheet">
</head>
<body>
<style>
    .form-group.required .control-label:after {
        content: " *";
        color: red;
        font-weight: bold;
    }
</style>
<div class="container-fluid">
    <div class="row"></div>
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
            <br/>
            @if(Session::has('success'))
                <p class="alert alert-success"><b>Congratulation!</b> Your email was successfully sent</p>
            @endif
            <h2 class="page-header">Send Email</h2>
            {!! Form::open(['class'=>'form-horizontal']) !!}
            <div class="form-group required {{ $errors->has('email')?'has-error':'' }}">
                {!! Form::label('email','Email',['class'=>'col-md-3 control-label']) !!}
                <div class="col-md-8">
                    {!! Form::text("email",null,["class"=>"form-control"]) !!}
                    @if ($errors->has('email'))
                        <span class="help-block">
                    <strong>{{ $errors->first('email') }}</strong>
                </span>
                    @endif
                </div>
            </div>
            <div class="form-group required {{ $errors->has('subject')?'has-error':'' }}">
                {!! Form::label('subject','Subject',['class'=>'col-md-3 control-label']) !!}
                <div class="col-md-8">
                    {!! Form::text("subject",null,["class"=>"form-control"]) !!}
                    @if ($errors->has('subject'))
                        <span class="help-block">
                    <strong>{{ $errors->first('subject') }}</strong>
                </span>
                    @endif
                </div>
            </div>
            <div class="form-group required {{ $errors->has('msg')?'has-error':'' }}">
                {!! Form::label('msg','Message',['class'=>'col-md-3 control-label']) !!}
                <div class="col-md-8">
                    {!! Form::textarea("msg",null,["class"=>"form-control"]) !!}
                    @if ($errors->has('msg'))
                        <span class="help-block">
                    <strong>{{ $errors->first('msg') }}</strong>
                </span>
                    @endif
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-6 col-md-push-3">
                    {!! Form::button("<i class='glyphicon glyphicon-floppy-disk'></i> Save",["type" => "submit","class"=>"btn
                btn-primary"])!!}
                </div>
            </div>
            {!! Form::close() !!}
        </div>
        <div class="col-md-3"></div>
    </div>
</div>
<!-- JavaScripts -->
<script src="{{ asset('js/jquery-1.11.2.min.js') }}"></script>
<script src="{{ asset('bootstrap-3.3.6/js/bootstrap.min.js') }}"></script>
</body>
</html>

mail_body.blade.php
{!! nl2br($body) !!}

Step 6: Create controller file TutorialController.php in here C:\wamp\www\test_laravel\app\Http\Controllers 
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class TutorialController extends Controller
{
    public function getSendEmail()
    {
        return view('tutorial.send_email');
    }

    public function postSendEmail(Request $request)
    {
        $validator = Validator::make($request->all(),
            [
                'email' => 'required|email',
                'subject' => 'required',
                'msg' => 'required'
            ]);
        if ($validator->fails())
            return back()->withErrors($validator)->withInput();
        Mail::send('tutorial.mail_body', ['body' => $request->msg], function ($message) use ($request) {
            $message->to($request->email)->subject($request->subject);
        });
        return back()->withSuccess(1);
    }
}

How to test? open your browser and type http://localhost/test_laravel/public/tutorial/send-email. You will see this screen

 

Laravel Html, Form class not found in Laravel 5

Starting from Laravel 5, Html and Form class were removed by default.



To use it, you can use this package laravelcollective/html (https://laravelcollective.com).

* Suppose that your Laravel project is at C:\wamp\www\test_laravel.

Step 1: edit C:\wamp\www\test_laravel\composer.json file and insert this line

"laravelcollective/html": "5.2.*"

 

Step 2: Open command prompt (CMD) and go to root folder (C:\wamp\www\test_laravel) and type composer update

 

 Note: It take some minute to update it. Please be patient.

Step 3 : Edit file C:\wamp\www\test_laravel\config\app.php and add
Collective\Html\HtmlServiceProvider::class in providers array. 
'providers' => [
        .......
        .......
        Collective\Html\HtmlServiceProvider::class,
    ],
And add 'Form' => Collective\Html\FormFacade::class,'Html' => Collective\Html\HtmlFacade::class,
in aliases array.
    'aliases' => [
        ..............
        ..............
        'Form' => Collective\Html\FormFacade::class,
        'Html' => Collective\Html\HtmlFacade::class,
    ],

That's all. I hope it is working now.

Laravel Layout and blade template introduction

For example, you create 2 veiws (main.blade.php and view1.blade.php) and its content are as below

main.blade.php
<html>
<head>
    <title>Laravel</title>
<body>
<h1>Header</h1>
@yield('content')
<h4>Footer</h4>
</body>
</html>

view1.blade.php
@extends('main')
@section('content')
    Here is my body
@endsection

Please check the result below.
If you render main.blade.php, you will see like this

And if you render view1.blade.php, you will see like this


Based on the code and result. Let me explain how blade engine work.
 

@yield('content') is used in a main or master view. you can put @yield code at any part of your view. Putting this line of code mean that this section will be replaced by other view.

And how to use the layout file (main.blade.php)  in normal view (view1.blade.php)

@extends('main') putting this code in view1.blade.php file mean that you want to use view main.blade.php and replace some section in side the file.

@section('content')...@endsection it mean that you want to replace the @yield('content') section in main.blade.php with the code inside this section block.

  • Blade Template 
blade template in Laravel is used to remove php block <?php ?>. It mean that normally if you want to write
php code in view file, you have to write it in this block <?php ?>. But in blade template, you can use @ instead.

Ex:
{{ $var }}    =>   <?php echo htmlentities($var);?>  
{!! $var  !!}   =>  <?php echo $var;?>
@if ....@endif    => <? if(){....}  ?>

I hope you can understand because it is very basic.

Laravel Project - Restaurant Management System

Are you a PHP programmer? Have you ever thought that you cannot do anything after finishing your programming training course? It is because you don’t know the goal of your study, and no one tell you which part of any completed project will use your piece of code.

In this tutorial, I would like to show the kind of system that you can develop after reading all the tutorials in this blog. It is also the goal that you want you to achieve.

Below are the screenshots of the restaurant management project. And later, I will share you all the pieces of code that you can use for this whole project.

To make you feel easy to catch all the points of the following tutorials, you should have some knowledge of PHP, MySQL, MVC architecture concept, HTML, CSS, Javascript, JQuery, Bootstrap.

Cashier screen



Admin screen




























Admin dashboard

Login screen - PC View
Login screen - mobile view




How to use route, controller, model and view in Laravel

In this tutorial, I am going to show you how to create and use route, controller, model and view. I show you the basic only because it can make you easy to understand and remember. If you want to know more detail on how to use it, please go to https://laravel.com

Suppose that the project folder is C:\wamp\www\test_laravel
  • View
To create view, you have to create it in this folder C:\wamp\www\test_laravel\resources\views. And its extension is .blade.php (Ex: viewname.blade.php).
  • Model
In order to create model, you have to create it in this folder C:\wamp\www\test_laravel\app. And its extension is .php (Ex: Student.php) 
    • Model name should start with big letter and singular noun. Ex: Student.php, Customer.php, ProductCategory.php (2 words)
    • For its content, you have to create a class, and the class name should be the same to the filename. and it have to extends from Model.
 
    • The screenshot above mean that model Customer represents customers table in the database. The table name should be lowercase and plural noun. Ex: customers, users, product_categories (2 words)
  • Controller
In order to create controller, you have to create it in this folder C:\wamp\www\test_laravel\app\Http\Controllers. And its extension is .php
    • Controller name have to be in this format CustomerController (name of controller start with big letter + Controller)
    • For its content, you have to create a class, and the class name should be the same to the filename. and it have to extends from Controller
    • And inside class, we have to create methods and those method name have to start with get or post. Ex: getIndex(), getDelete(), postCreateCustomer() (2 words). Note: get is used for get request. And post is used to post request.
 
  • Route
 To use route in Laravel, you no need to create the file. Just go to edit the file in here C:\wamp\www\test_laravel\app\Http\routes.php

Route is front door to allow access to the system. So you cannot access view and controller without route.

This is the format of route.

Route::get('URI','Action')                  // Action can be function or controller method 
Route::controller('URI','ControllerName')

Ex: 
// route to view
Route::get('/',function(){
     return view('view1');
});

// route to controller action
Route::get('customer_list','CustomerController/getIndex');

// route to controller
Route::controller('customer','CustomerController');   // by default, it will run getIndex() method

How to run it? Go to browser and type
http://localhost/test_laravel         // it will point to route 1
http://localhost/test_laravel/customer_list              // it will point to route 2
http://localhost/test_laravel/customer                  // it will point to route 3. And method getIndex() will execute

Friday, June 17, 2016

What to do after laravel installation?

Before starting to learn any framework, you have to know
  • Where is the Model, View and Controller folder? (Generally, framework use MVC architecture concept. And developer need to know those 3 main folders to write their code)
  • Where is the configuration files?
  • What are its features, process and architecture (https://laravel.com)

What is MVC stand for?
  • M (Model) : for representing database tables and its relationship. So if you want to do any action with table in the database, you can do it with Model instead. 
  • V (View): for showing data on the screen for user to interact with
  • C (Controller): for coding of all processes in the system. Ex: validate data, insert, delete, update, read 
 

Below are the files and folder that we usually use in Laravel framework
suppose that this is the root folder of your project C:\wamp\www\test_laravel
  •  C:\wamp\www\test_laravel\composer.json is used to manage the dependencies of the package. This means that Composer will pull in all the required libraries, dependencies and manage them all in one place. (The meaning is the same to Linux yum repository). Note: after you change some content in this file, you have to go to command prompt (CMD) and go to current working folder (C:\wamp\www\test_laravel), then type composer update
 
  • C:\wamp\www\test_laravel\app\Http\routes.php is the only one front door which can allow access to the system.
  • C:\wamp\www\test_laravel\.env is a global parameters file. We can use all parameters declare in this file for the whole project.
  • C:\wamp\www\test_laravel\config store all configuration files of Laravel framework
  • C:\wamp\www\test_laravel\app store your model files
  • C:\wamp\www\test_laravel\resources\views store all your view files
  • C:\wamp\www\test_laravel\app\Http\Controllers store all your controller files
 

How to install Laravel framework

Suppose that you are using Window with Wamp installed, and C:\wamp\www is the root folder of your project. 

Step 1: open command prompt (CMD) and type php –v. and make sure you will return information like this. 

 

If not, please add your php path (C:\wamp\bin\php\php5.5.12) in the system variable 

 

Step 2: download and install composer https://getcomposer.org/Composer-Setup.exe

Step 3: open command prompt (CMD) and type composer. and make sure you will return information like this. 

 

If not, please add your composer path (C:\ProgramData\ComposerSetup\bin) in the system variable. 

 

Step 4: 
Note: In order to make the installation process faster, please go to disable xdebug in your php.ini file. 

 
Then open command prompt (CMD) and go to root folder (C:\wamp\www). Then run 

              composer create-project --prefer-dist laravel/laravel test_laravel

It means that your laravel project will install to test_laravel folder which locate in C:\wamp\www 

 

   

Step 5: Once the installation is done, please go to browser and type http://localhost/test_laravel/public 



If you see the screen like this, it means your laravel project was successfully installed.