0
votes

I need to insert sub categories into my main categories. I have already done all the work for Showing, Adding, Editing, and Deleting parent Categories. But now im stuck with how to actually add a sub category to one of my parents category.

Here is how the table looks like for the category's and sub categories.

Categories Table

As you can see I already Have a sub category under iPhone's, which I added manually through the database. To add a sub category to a main category, I just click on the + sub-Category link which takes me to the form to add sub category.

Here i my route to show and add a sub category:

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'],
    ]);


});

Here is my CategoriesController.php:

It is shortened just to show sub-categories functions. This is where I'm having trouble adding a sub category to a parent category

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');
    }

}

My Category.php Model:

<?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');
    }

}

My add sub category form:

 <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>

And my Database structure:

My DB structure

I particulary need help in my addPostSubCategories() function in my CategoriesController, because right now if I add a new SUB category, it just adds a new Parent Category, not a sub category

1

1 Answers

2
votes

Visit here to see a detailed explanation: https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

Here's what you want:

/**
 * @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');
}