PHP code example of moraesgil / entity-validator-trait

1. Go to this page and download the library: Download moraesgil/entity-validator-trait 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/ */

    

moraesgil / entity-validator-trait example snippets


...

//Your Model
use Traits\Entities\EntityValidatorTrait;  //<<<<< add this line

class YourLaravelEntity extends Model {
   use EntityValidatorTrait;

   protected $table = 'samples';

   protected $rules = [ //<<<<< add this array with validation
      'id' => '

// Your  Controller
class SampleController extends Controller
{
   public function store(Request $request)
   {
      $model = new YourLaravelEntity();
      //here is the magic
      if ($model->hasRules()) { //<<<<< check has rules
         if (!$model->validate($request->all())) { //<<<<< validate
            return response()->json($model->errors, 400);
         }
      }
      return response()->json($model->create($request->all()), 201);
   }

   public function update(Request $request)
   {
      //here is the magic
      if ($model->hasRules()) { //<<<<< check has rules
         if (!$model->validate($request->all(), $id)) { //<<<<< validate
            return response()->json($model->errors, 400);
         }
      }
      return response()->json($model->update($request->all()), 201);
   }
}