Home > Mobile >  How to update an array field in laravel?
How to update an array field in laravel?

Time:09-24

EDIT FORM

<div class="form-group mb-3">
                        <label>Country:</label>
                        <div class="col-sm-4">
                        <select  id="country-dd" name="country[]" class="js-example-basic-multiple form-control" multiple="multiple">
                        @foreach($countries as $country)
                        <option value="{{$country->id }}" {{in_array($country->id, explode(',',$user->country)) ? 'selected' : '' }}> {{$country->name}}</option>
                        @endforeach
                        </select>
                    </div>
                    </div>

CONTROLLER

public function updateuser(Request $request, $id)
    {
        // dd($request->all());
        $request->validate([
            'name'=>'required',
            'email'=>'required|email|unique:users',
            'country'=>'required',
            'state'=>'required',
            'city'=>'required',
            'role_id'=>'required'

        ]);
        $name = $request->name;
        $email=$request->email;
        $country=implode(',',$request->country);
        $state=implode(',',$request->state);
        $city=implode(',',$request->city);
        $role_id=$request->role_id;
        
        User::whereId($id)->update($request->all());

        return redirect()->route('viewuser');
    }

ROUTE

Route::put('/updateuser/{id}',[UserController::class,'updateuser'])->name('updateuser');

If I update a record. It just reloads the page and there is no error. Please correct me if I am doing wrong. Thanks in advance.

CodePudding user response:

Try in the CONTROLLER:

public function updateuser(Request $request, $id)
    {
        $request->validate([
            'name'=>'required',
            'email'=>'required|email|unique:users',
            'country'=>'required',
            'state'=>'required',
            'city'=>'required',
            'role_id'=>'required'

        ]);
        $user = User::findOrFail($id);
        $user->name = $request->name;
        $user->email=$request->email;
        $user->country=implode(',',$request->country);
        $user->state=implode(',',$request->state);
        $user->city=implode(',',$request->city);
        $user->role_id=$request->role_id;
        $user->update();
       
        return redirect()->route('viewuser');
    }

Try in the form:

<form action="{{ route('updateuser',$data->id) }}" method="POST" enctype="multipart/form-data">
    @method('PUT')
    @csrf


    ALL YOUR INPUTS HERE


    <div class="card-footer">
        <button type="submit" class="btn btn-primary mt-1 pr-4 pl-4">Update</button>
    </div>

</form>

Route

Route::match(['put', 'patch'], 'updateuser/{id}', [UserController::class,'updateuser'])->name('updateuser');
  • Related