Saturday, June 18, 2016

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
 

1 comment:

Helilink said...

Hi Senghok, Appreciated the tutorial. I had to do the following to make it work, and maybe you could add these comments to other tutorials. Need to download and install form&html components from laravelcollective.com. also needed to add js and css to public folders, maybe a cdn reference would be simplier. But liked the tutorial and encourage you to continue. Well done.