How to Store Data from select html tag to DB and display it...Laravel

Viewed 365

Laravel

I have 3 tables

1- users => id + name + email + password

2- categories => id + name

3- category_user => user_id + category_id

I want the users to choose their favorite categories so that only the articles for that category appear.

here the page to select category:

<div class="form-group">
        <label for="body">Category</label>
        <select name="categories[]" id="" multiple>
            @foreach ($categories as $category)
            <option value="{{$category->id}}">{{$category->name}}</option>
            @endforeach
        </select>

how can I store this data in the category_user table? (with validate)

Also, how can I display only articles belonging to the selected categories?

1 Answers

If you dump and die your request data in controller, you will see categories as an array. you can iterate through categories by a foreach loop and save it to category_user table. Don't forget to use current user id as user_id.

foreach ( $request->categories as $categoryId ) {
    CategoryUser::create( [ 'user_id' => auth()->user()->id, 'category_id' => $categoryId ] )
}

For display need some more information about articles table. Is one article belongs to one or many category?

Related