0
votes

I'm editing a Laravel 4.3 site and I have a db table called categories which has the following fields:

id parent_id name I'm trying to output a list in my view of categories, and their subcategories:

Category Another Category Subcat Subcat Subcat I'm not really sure of the best way of achieving this and hoping someone can help point me in the right direction :-)

this is my controller

public function store(Request $request) {

    $this->validate($request, [

        'name' =>'required'

    ]);




    $category= new Category;

    $category= Category::with('children')->whereNull('parent_id')->get();

    $category->name =$request->name;

    $category->save();}
1
You've posted the code to store the category, post your code that you tried to get the categories and subcategories. - Sethu
Are you sure this is right? Category::with('children')->whereNull('parent_id')->get(), because if the parent it null how the children will be there? - Sethu
What are you trying to archive? Are you trying to store the categories and retrieve the categories? - Sethu

1 Answers

0
votes

I hope this would help you

Method to store the data:

public function store(Request $request) {

    $this->validate($request, [
        'name' =>'required',
        'parent_id' => 'nullable|exists:category,id', //This will check the parent availability
    ]);


    $category= new Category;

    if ($request->has('parent_id')) {
        $category->parent_id =$request->parent_id;
    }

    $category->name =$request->name;
    $category->save();

    return $category;
}

Method to retrieve all data:

public function index() {
    $categories = Category::with('children')->all();

    return $categories;
}

Method to get category by id :

public function categoryById(Category $category) {
    $category = Category::with('children')->where('id', $category->id)->first();

    return $category;
}