validate

The Request::validate() response is optional. For example if you put a route parameter in the method, it will redirect to the route given with the error messages that validator collects. The other option is, if you are using an ajax call to direct request to the controller, you can leave the route paramerter to an empty '' string.

// if route parameter contains a value
Request::validate('/register', [
    'email' => ['required', 'email'],
    'username' => ['required', 'unique:users'],
    'password' => ['required'],
]);

// if route parameter has no value
Request::validate('', [
    'email' => ['required', 'email'],
    'username' => ['required', 'unique:users'],
    'password' => ['required'],
]);

If you use the empty route parameter, this will now redirected to any routes instead it returns a validationError index with all the errors that the validator collects. This option is best for ajax calls because you can convert validationError to json and return it back to the ajax and you can now do what ever you want to do with the data.

use App\Core\Auth;
use App\Core\Request;

class ProfileController
{
    public function update()
    {
        // the route parameter which is the first parameter
        // is an empty string. This is an example of dealing
        // with ajax request.
        $request = Request::validate('', [
            'email' => ['required', 'email'],
            'name' => ['required']
        ]);

        // we check if the validationError is empty
        if (empty($request['validationError'])) {
            $user_id = Auth::user('id');

            $update_data = [
                'email' => "$request[email]",
                'fullname' => "$request[name]"
            ];

            $response = DB()->update('users', $update_data, "id = '$user_id'");

            echo json_encode($response);
        }else{
            // if the validationError if not empty,
            // now we pass the validationError back to the ajax
            echo json_encode($request['validationError']);
        }
    }
}

Last updated