Wednesday, December 18, 2019

Laravel Custom Data Validation | Validate Request Data And Return Appropriate Error Message

Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the Illuminate\Http\Request object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an exception will be thrown and the proper error response will automatically be sent back to the user. In the case of a traditional HTTP request, a redirect response will be generated, while a JSON response will be sent for AJAX requests.
<?php
namespace App\Http\Controllers;

use Validator;
use App\Models\Users;
use Illuminate\Support\Facades\Log;

class RegistrationController extends ControllerBase {
    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function register() {
        if ($this->isLoggedIn()) {
            $this->setErrorMessage("Already logged in");
            throw new \Exception("Already logged in");
        }

        // if data is json formatted
        if (true) {
            $data = json_decode(request()->getContent(), true);

            request()->merge($data);
        }

        // custom messaged will show when validation fail
        // for example if name is missing will return 'The Name field is required'
        // we can define full message without using :attribute like 'email.unique'
        $customMessages = [
            'required' => 'The :attribute field is required.',
            'in' => 'The :attribute field has invalid data',
            'password.required' => 'Password required',
            'email.unique' => 'Email address must be unique'
        ];

        // used to set display name against key
        // for example if email is required then 'The Email Address field is required'
        $attributes = [
            'name' => 'Name',
            'email' => 'Email Address',
            'password' => 'Password',
            'status' => 'Status'
        ];

        $validator = Validator::make(request()->all(), [
            'name' => 'required|max:70',
            'email' => 'required|email|max:70|unique:users',
            'password' => 'required|min:6|max:70',
            'status' => 'required|in:pending',
        ],  $customMessages, $attributes);

        $validator->after(function($validator) {
            // If some validation failed
            if (true) {
                $validator->errors()->add('field', 'The field has invalid data');
            }
        });

        if ($validator->fails()) {
            Log::error($validator->errors());
            return response()->json(["success" => 0, "error" => $validator->errors()->first()], 200);
        }

        $user = Users::create(request([
            'name',  'email', 'password', 'status'
        ]));

        return response()->json(["success" => 1, "user_id" => $user->id]);
    }
}

1 comment:

  1. Thank you for sharing this informative content. Looking forward to reading more.
    Laravel Development Services

    ReplyDelete