How to store ids in an array in laravel

29 views Asked by At

`I have a table named users. Each user can have multiple branch_ids.I have a pivot table user_branch that stores user_ids and branch_ids.In my user_branch table the data is saved well but in my users table am failing to save the array of branchids under the branch_id column for each user.

blade.php

<div class="col-md-12">
           <div class="form-group mb-3">
                 <label for="#" class="form-label">{{ _trans('common.Branch') }} <span class="text-                
                        danger">*</span></label>                                                                                                           
                   <select name="branch_id[]" class="form-control select2" multiple="multiple"  
                          required="required">    
                                <option value="" disabled>{{ _trans('common.Choose One') }}
                                   </option>
                                 @foreach ($data["branches"] as $branch)
                                   <option value="{{ $branch->id }}">{{ $branch->name }}</option>
                                 @endforeach
                         </select>

                          @if ($errors->has('branch_id'))
                              <div class="error text-danger">{{ $errors->first('branch_id') }}                        
                          @endif
              </div>

           </div>

user controller


  public function store(UserStoreRequest $request)
    {
        // dd($request->input('branch_id'));

        if (appMode()) {
            Toastr::error(_trans('message.You cannot do it for demo'), 'Error');
            return redirect()->back();
        }
    
        try {
           
            //dd($data['role_permissions']);
            // Validate the request
            $validator = \Validator::make($request->all(), $request->rules());
    
            if ($validator->fails()) {
                // Log or dump validation errors
                Log::error($validator->errors());
                dd($validator->errors());
            }

    
            $user = new User;
            $user->employee_id = $request->input('employee_id');
            $user->designation_id = $request->input('designation_id');
            $user->department_id = $request->input('department_id');
            $user->shift_id = $request->input('shift_id');
            $user->role_id = $request->input('role_id');
            $user->email = $request->input('email');
            $user->phone = $request->input('name');
            $user->gender = $request->input('gender');
            $user->address = $request->input('address');
            $user->religion = $request->input('religion');
            $user->blood_group = $request->input('blood_group');
            $user->joining_date = $request->input('joining_date');
            $user->end_date = $request->input('end_date');
            $user->marital_status = $request->input('marital_status');
            $user->work_group = $request->input('work_group');
            $user->birth_date = $request->input('birth_date');
            $user->name = $request->input('name');
            $user->branch_id = $request->input('branch_id');
            $user->save();

            $user->branches()->sync($request->input('branch_id'));
            
            Toastr::success(_trans('message.User created successfully'), 'Success');
            return redirect()->route('user.index');
        } catch (\Exception $e) {
            // Log or handle the exception
            Log::error($e);
            Toastr::error(_trans('response.Something went wrong!'), 'Error');
            return back();
        }
    }

user Model

protected $casts = [
        'email_verified_at' => 'datetime',
        'permissions' => 'array',
        'company_id' => 'integer',
        'branch_id' => 'array',`

   public function branches()
    {
        return $this->belongsToMany(Branch::class, 'user_branch', 'user_id', 'branch_id');
    }
    public function getBranchIdsAttribute()
    {
        return $this->branches->pluck('id')->toArray();
    }
    public function attachBranchesToUser($userId)
    {
        $user = User::find($user_id);

        if ($user) {
            $branch_id = [1, 2]; // Replace with your branch IDs
            $user->branches()->attach($branch_id);

            return response()->json(['message' => 'Branches attached to user successfully']);
        } else {
            return response()->json(['error' => 'User not found'], 404);
        }
    }


branch model

public function users()
    {
           return $this->belongsToMany(User::class, 'user_branch', 'branch_id', 'user_id');
    }

0

There are 0 answers