How To Update hasMany relationship data with multiple row at a time in Laravel?

Viewed 63

I want to update SubCategory, which has a relationship with Category as a hasMany relationship. Now I want to update both category and subcategory at a time from one form. I want to update every subcategory which belongs to the category. But I can't do that. Here is category model:

 class Category extends Model
 {
    use HasFactory;
    protected $guarded=[];
    public function subcategory(){
    return $this->hasMany('App\Models\SubCategory');
}

Here is subcategory model:

class SubCategory extends Model
{
    use HasFactory;
    protected $guarded=[];
    public function category(){
    return 
   $this>belongsTo('App\Models\Category','category_id','id');
}

here is update function in controller:

 public function categoryUpdate(Request $request,$id){
    
 if (is_null($this->user) || !$this->user->can('categories-update')) {
        
        abort(403, 'Sorry !! You are Unauthorized  !');
    }
    $request->validate([
        'name' =>  'required|max:191',
        'status' => 'required',     
   ]);
        $Category=Category::findOrFail($id);
        $Category->name = $request->name;
        $Category->slug = Str::slug($request->name);
        $Category->status = $request->status;
  
        $Category->updated_by=Auth::user()->id;
        $Category->update();
        
        if($request->subcategory_name !=['']){
            foreach($request->subcategory_name as $subcat){
                if($subcat !=''){
                    SubCategory::create([
                        'name'=>json_encode($subcat),
                        'slug'=>Str::slug(json_encode($subcat)),
                        'category_id'=>$id,
                        'created_by' =>Auth::user()->id,
                      ]);
                }
            }
        }
        Alert::success('Success','Category has been updated successfully!');

        return redirect()->route('category.index');

}

I don't know the code to update multiple subcategories at a time.

Here is the Html form

<form action="{{ route('category.update', $data->id) }}" method="POST">
                        @csrf

                        <div class="form-group">

                            <label for="" class="mb-2">Category name</label>

                            <input name="name" class="form-control" value="{{ $data->name }}" type="text"
                                @error('name') is-invalid @enderror" placeholder="Name">
                            @error('name')
                                <div class="text-danger">* {{ $message }}</div>
                            @enderror
                        </div><br>
                        <div class="form-group">
                            <label for="" class="mb-2">SubCategory name</label>
                                @foreach ($subcat as $sub)
                                <div class="d-flex w-70 justify-content between mb-2">
                                <input name="subcategoryname[]" id="subcategoryname" class="form-control w-50" type="text" value="{{json_decode($sub->name)}}"></input>

                                <button  onclick="deleteSubcategory({{$sub->id}})" id="delete_subcat"  class="btn btn-danger btn-sm ms-2"><i
                                    class="fa fa-trash text-dark" style="font-size:20px;color:white!important"
                                    aria-hidden="true"></i></button>
                                </div>
                                @endforeach


                        </div><br>
                        <div class="form-group mt-2">
                            <label for="" class="mb-2">Add New SubCategory</label>
                            <div class="subcategory w-50">
                                <div class="d-flex mb-2">
                                    <input name="subcategory_name[]" class="form-control" id="name" type="text"
                                        placeholder="Name" multiple>
                                    <span id="add" class="btn btn-dark ms-3">+</span>

                                </div>
                            </div>

                            <div class="form-group mt-2">
                                <label for="" class="mb-2">Status</label>
                                <br>
                                <select name="status" class="form-control" style="width:40%"
                                    @error('status') is-invalid @enderror">
                                    <option value="">--Select Status--</option>

                                    <option value="Active" @if ($data->status == 'Active') selected @endif>Active
                                    </option>
                                    <option value="Inactive" @if ($data->status == 'Inactive') selected @endif>Inactive
                                    </option>
                                </select>

                                @error('status')
                                    <div class="text-danger">* {{ $message }}</div>
                                @enderror
                            </div>
                            <div class="form-group mt-4 d-flex justify-content-between">
                                <button type="button" class="btn btn-secondary btn-sm"
                                    data-bs-dismiss="modal">Cancel</button>


                                <input class="btn btn-primary btn-sm"type="submit" value="Update">
                            </div>

                    </form>
1 Answers

The create method takes array of records you want to save. So you can build an array and pass that array to the create method on the SubCategory.

if($request->subcategory_name !=['']){
$subCategories = [];
foreach($request->subcategory_name as $subcat){
    if($subcat !=''){
        $subCategories[] = [
            'name'=>json_encode($subcat),
            'slug'=>Str::slug(json_encode($subcat)),
            'category_id'=>$id,
            'created_by' =>Auth::user()->id,
        ];
    }
}
SubCategory::updateOrCreate(['name', 'slug'], $subCategories);
}
Related