添加子类别 - Laravel 5.2

时间:2016-04-03 16:58:23

标签: php mysql laravel laravel-5.2

我需要在我的主要类别中插入子类别。我已经完成了显示,添加,编辑和删除父类别的所有工作。但现在我仍然坚持如何将子类别添加到我的父类别中。

以下是该类别和子类别的表格。

Categories Table

正如你所看到的,我已经在iPhone下有一个子类别,我通过数据库手动添加。要将子类别添加到主类别,我只需单击+子类别链接,该链接将我带到表单以添加子类别。

这是我展示和添加子类别的路线:

Route::group(["middleware" => 'admin'], function(){

    /** More category routes here -->, just hidden for shortness **/


    /** Show the Admin Add Sub-Categories Page **/
    Route::get('admin/categories/addsub/{id}', [
        'uses' => '\App\Http\Controllers\CategoriesController@addSubCategories',
        'as'   => 'admin.category.addsub',
        'middleware' => ['auth'],
    ]);


    /** Post the Sub-Category Route **/
    Route::post('admin/categories/postsub/{id}', [
        'uses' => '\App\Http\Controllers\CategoriesController@addPostSubCategories',
        'as'   => 'admin.category.postsub',
        'middleware' => ['auth'],
    ]);


});

这是我的CategoriesController.php:

只是为了显示子类别功能而缩短。这是我在将子类别添加到父类别

时遇到问题的地方
class CategoriesController extends Controller
    /**
     * Return the view for add new sub category
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function addSubCategories($id) {

        $category = Category::findOrFail($id);

        return view('admin.category.addsub', compact('category'));
    }


    /**
     * @param $id
     * @param CategoryRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addPostSubCategories($id, CategoryRequest $request) {

        // Find the Parent Category ID
        $category = Category::findOrFail($id);

        // Insert into categories where the Parent_id = to the category ID
        $categories = Category::where('parent_id', '=', $category);


        // Assign $category to the Category Model, and request all validation rules
        $categories = new Category($request->all());

        // Then save the newly created category in DB
        $categories->save();

        // Flash a success message
        flash()->success('Success', 'Sub Category added successfully!');

        // Redirect back to Show all categories page.
        return redirect()->route('admin.category.show');
    }

}

我的Category.php模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{

    protected $table = 'categories';

    protected $fillable = ['name'];

    protected $guarded = ['id'];


    public function parent() {
        return $this->belongsTo('App\Category', 'parent_id');
    }



    public function children() {
        return $this->hasMany('App\Category', 'parent_id');
    }

}

我的添加子类别表单:

 <form role="form" method="POST" action="{{ route('admin.category.postsub', $category->id) }}">
                    {{ csrf_field() }}
                    <li class="collection-item blue">
                        <h5 class="white-text text-center">
                            Sub-Category to {{ $category->name }}
                        </h5>
                    </li>
                    <li class="collection-item">
                        <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
                      <input type="text" class="form-control" name="name" value="{{ old('name') }}" placeholder="Add Sub-Category">
                            @if($errors->has('name'))
                                <span class="help-block">{{ $errors->first('name') }}</span>
                            @endif
                        </div>
                    </li>
                    <li class="collection-item blue">
                        <div class="form-group text-center">
                            <button type="submit" class="btn btn-link grey lighten-5">Create Sub-Category</button>
                        </div>
                    </li>
                </form>

我的数据库结构:

My DB structure

我特别需要在我的CategoriesController中的addPostSubCategories()函数中提供帮助,因为现在如果我添加一个新的SUB类别,它只会添加一个新的父类别,而不是一个子类别

1 个答案:

答案 0 :(得分:2)

访问此处查看详细说明:https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

这是你想要的:

/**
 * @param $id
 * @param CategoryRequest $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function addPostSubCategories($id, CategoryRequest $request) {

    // Find the Parent Category
    $category = Category::findOrFail($id);

    // Create the new Subcategory
    $subcategory = new Category($request->all());

    // Save the new subcategory into the relationship
    $category->children()->save($subcategory);

    // Flash a success message
    flash()->success('Success', 'Sub Category added successfully!');

    // Redirect back to Show all categories page.
    return redirect()->route('admin.category.show');
}