PHP code example of nguyenvantruc92 / laravel-validation

1. Go to this page and download the library: Download nguyenvantruc92/laravel-validation library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nguyenvantruc92 / laravel-validation example snippets


Prettus\Validator\Contracts\ValidatorInterface::RULE_CREATE
Prettus\Validator\Contracts\ValidatorInterface::RULE_UPDATE

use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    protected $rules = [
        'title' => '


use \Prettus\Validator\LaravelValidator;

class PostValidator extends LaravelValidator {

    protected $rules = [
        ValidatorInterface::RULE_CREATE => [
            'title' => '


protected $messages = [
    '


protected $messages = [
    'email.


protected $attributes = [
    'email' => 'E-mail',
    'obs' => 'Observation',
];



use \Prettus\Validator\Exceptions\ValidatorException;

class PostsController extends BaseController {

    /**
     * @var PostRepository
     */
    protected $repository;
    
    /**
     * @var PostValidator
     */
    protected $validator;

    public function __construct(PostRepository $repository, PostValidator $validator){
        $this->repository = $repository;
        $this->validator  = $validator;
    }
   
    public function store()
    {

        try {

            $this->validator->with( Input::all() )->passesOrFail();
            
            // OR $this->validator->with( Input::all() )->passesOrFail( ValidatorInterface::RULE_CREATE );

            $post = $this->repository->create( Input::all() );

            return Response::json([
                'message'=>'Post created',
                'data'   =>$post->toArray()
            ]);

        } catch (ValidatorException $e) {

            return Response::json([
                'error'   =>true,
                'message' =>$e->getMessage()
            ]);

        }
    }

    public function update($id)
    {

        try{
            
            $this->validator->with( Input::all() )->passesOrFail( ValidatorInterface::RULE_UPDATE );
            
            $post = $this->repository->update( Input::all(), $id );

            return Response::json([
                'message'=>'Post created',
                'data'   =>$post->toArray()
            ]);

        }catch (ValidatorException $e){

            return Response::json([
                'error'   =>true,
                'message' =>$e->getMessage()
            ]);

        }

    }
}