Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

php - How can I display subcategories of specific category id in a dropdown. Within laravel

So after figuring out how to display categories and sub categories in a dropdown. I have been trying to figure out if its possible to display specific subcategories of a category class.

These are the Categories I set up Categories After making the categories I created subcategories the ones shown here are based on the first cat ID - selectionsSubCategories

The cat and subcat were created as follows;

AppServiceProvider.php

<?php

namespace AppProviders;

use AppCategory;
use IlluminateSupportFacadesView;
use IlluminateSupportServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('categories', Category::orderBy('name')->get());
    }
}

Web.php

<?php

use AppHttpControllersCategoryController;
use AppHttpControllersSubcategoryController;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

//Route::get('/Home', function () {
//    return view('welcome');
//});

Auth::routes();

Route::get('/email', function () {
   return new AppMailNewUserWelcomeMail();
});

Route::post('follow/{user}', 'FollowsController@store');

Route::get('dashboard/profile', 'ProfilesController@show');

Route::get('/search','SearchController@search');

Route::get('/home', 'HomeController@index');

Route::get('/categories', 'CategoryController@index');

Route::get('/', 'PostsController@index');
Route::get('/p/create', 'PostsController@create');
Route::post('/p', 'PostsController@store');
Route::get('/p/{post}', 'PostsController@show');

//Route::prefix('/recipes')->group(function () {
//    Route::get('/create-step1', 'RecipesController@createStep1');
//    Route::get('/create-step2', 'RecipesController@createStep2');
//    Route::get('/create-step3', 'RecipesController@createStep3');
//    Route::get('/create-step4', 'RecipesController@createStep4');
//    Route::post('/create-step1', 'RecipesController@postCreateStep1');
//    Route::post('/create-step2', 'RecipesController@postCreateStep2');
//    Route::post('/create-step3', 'RecipesController@postCreateStep3');
//    Route::post('/create-step4', 'RecipesController@postCreateStep4');
//    Route::post('/remove-image', 'RecipesController@removeImage');
//});

Route::get('/recipes/create', 'RecipesController@create');
Route::get('subcategories/get/{id}', 'RecipesController@getStates');


Route::get('/profile/{user}', 'ProfilesController@index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfilesController@edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfilesController@update')->name('profile.update');

Category.php

  <?php
    
    namespace App;
    
    use IlluminateDatabaseEloquentModel;

class Category extends Model

{
    protected $fillable = [];


    public function subcategories(){
        return $this->hasMany('AppSubcategory');
    }

    public function posts(){
        return $this->hasMany('AppPost');
    }

}

?>

RecipesController.php

<?php

namespace AppHttpControllers;

use AppRecipe;
use IlluminateHttpRequest;
use IlluminateHttpResponse;
use IlluminateContractsFoundationApplication;
use IlluminateContractsViewFactory;
use IlluminateSupportFacadesDB;
use IlluminateViewView;

class RecipesController extends Controller
{
    public function index()
    {

        return view('recipes.index');
    }

    public function create()
    {

        $categories = DB::table('categories')->pluck("name","id");
        return view ('recipes.create', compact($categories));
    }

    public function getStates($id)
    {

        $subcategories = DB::table("subcategories")->where("category_id", $id)->pluck("name", "id");

        return json_encode($subcategories);
    }

}

recipes/create.blade.php

@extends('layouts.app')
@section('content')
    <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Multi Step Form | Recipes smartMeals</title>
</head>
<body>

<div class="container">
    <header>Create Your First Recipe</header>

    <div class="form-outer">
        <form action="#">

            <div class="page">
                <div class="title">What's your recipe:</div>

                <div class="field pt-1">

                    <div class="label pt-3">Title</div>
                    <input type="text" placeholder="Name the recipe">
                </div>

                <div class="field">
                    <label class="label pt-3">Description</label>
                    <div class="control pb-1">
                        <textarea class="textarea" placeholder="Lets cut to the cheese"></textarea>
                    </div>

                    <div class="field">
                        <button>Next</button>
                    </div>
                </div>
            </div>

            <div class="page">

                <div class="title pt-3">Recipe information:</div>

                <div class="field is-horizontal pt-3">
                    <div class="field-label is-normal">
                        <label class="label">Selections</label>
                    </div>

                    <div class="field-body">
                        <div class="field is-narrow">
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select>
                                        <option value="">--Select Selections--</option>
                                        @foreach($categories as $category)
                                        <option>{{$category -> name}}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="field is-horizontal pt-3">
                    <div class="field-label is-normal">
                        <label class="label">Selections type</label>
                    </div>

                <div class="field-body">
                    <div class="field is-narrow">
                        <div class="control">
                            <div class="select is-fullwidth">
                                <select name="subcatagories">
                                    <option>--Select Selection Type--</option>
                                </select>
                            </div> <div class="col-md-2"><span id="loader"><i class="fa fa-spinner fa-3x fa-spin"></i></span></div>

                        </div>
                        </div>
                    </div>
                </div>


    <div class="field pt-2">
                    <label class="label">Message</label>
                    <div class="control">
                        <textarea class="textarea" placeholder="Lets cut to the cheese"></textarea>
                    </div>

                    <div class="field">
                        <button>Next</button>
                    </div>
                </div>
            </div>


        </form>
    </div>
</div>

<script src="{{ asset('js/app.js') }}"></script>
<script src="{{ asset('js/custom.js') }}"></script>

</body>
</html>

@endsection

custom.js

$(document).ready(function() {

    $('select[name="categories"]').on('change', function(){
        var categoryId = $(this).val();
        if(categoryId) {
            $.ajax({
                url: '/subcategory/get/'+categoryId,
                type:"GET",
                dataType:"json",
                beforeSend: function(){
                    $('#loader').css("visibility", "visible");
                },

                success:function(data) {

                    $('select[name="subcategory"]').empty();

                    $.each(data, function(key, value){

                        $('select[name="subcategory"]').append('<option value="'+ key +'">' + value + '</option>');

                    });
                },
                complete: function(){
                    $('#loader').css("visibility", "hidden");
                }
            });
        } else {
            $('select[name="subcategory"]').empty();
        }

    });

});

I was hoping to change the section of code within recipes/create.blade.php;

<div class="field-body">
                        <div class="field is-narrow">
                            <div class="control">
                                <div class="select is-fullwidth">
                                    <select>
                                        <option value="">--Select Selections--</option>
                                        @foreach($categories as $category)
                                        <option>{{$category -> name}}</option>
                                        @endforeach
                                    </select>
                                &

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...