Home > Blockchain >  Call to a member function fails() on array in update() method
Call to a member function fails() on array in update() method

Time:09-12

In my method update() has some block of error conditions Call to a member function failed on array precisely that checks if $validations fails. I noticed that all the store() and updated() methods work correctly without the need for the conditional block. I just thought it would be nice to insert these conditions.


    namespace App\Http\Controllers;

    use App\Http\Requests\HunterRequest;
    use Illuminate\Http\Request;
    use App\Models\HunterModel;
    
    class HunterController extends Controller {
    
        public function store(Request $request)
        {
            $validations = $request->validate();
            if ($validations->fails()){
               return redirect()->back();
            }
            HunterModel::create($validations);
            return redirect()->to('/');   
        }
    
        public function update(Request $request, $id)
        {
            $validations = $request->validate();
            if ($validations->fails()){ // Call to a member function fails() on array
               return redirect()->back();
            }
            HunterModel::where('id',$id)->update($validations);
            return redirect()->to('/');        
        }
    
    }

CodePudding user response:

$request->validate() expects an array of validation rules to validate the incoming request data against. You're not currently supplying anything so aren't actually performing any validation.

If validation is successful, the return value of that call will be an array of validated data, it is not an object and so doesn't have a fails() method (or any methods for that matter).

// $validations is an array
$validations = $request->validate([
    'field' => ['required'],
]);

If validation is not successful, Laravel will automatically redirect back to the caller sending all failuer errors messages.

Therefore, the following lines are redundant and should be removed as Laravel will handle failure scenarios for you:

if ($validations->fails()){
    return redirect()->back();
}

CodePudding user response:

you are using validate method for the validation logic, this method return an array ...

you should use make method to check validation's fails

 $validator = Validator::make($request->all(), [
            'smoeFiled' => 'required|.....',
       
    ]);

you should also provide the validator with validation rules.

see Laravel doc for more details.

  • Related