php - Laravel 5 validation in model

638

I have model like this

class test extends Model
{

public   $rules = [
    'title' => 'required',
    'name' => 'required',
];
protected $fillable = ['title','name'];
}

And controller like this

public function store(Request $request)
{
    $test=new test; /// create model object
        $validator = Validator::make($request->all(), [
             $test->rules
        ]);
        if ($validator->fails()) {
            return view('test')->withErrors($validator)
        }
        test::create($request->all());
 }

Validation show error like this

The 0 field is required.

I want show this

The name field is required.
The title field is required.

265

Answer

Solution:

I solve it

public function store(Request $request)
{
  $test=new test; /// create model object
    $validator = Validator::make($request->all(),$test->rules);
    if ($validator->fails()) {
        return view('test')->withErrors($validator)
    }
    test::create($request->all());
}
398

Answer

Solution:

You are doing it the wrong way. Therules array should either be in your controller or better in a Form Request.

Let me show you a better approach:

Create a new Form Request file withphp artisan make:request TestRequest.

ExampleTestRequest class:

namespace App\Http\Requests;

use App\Http\Requests\Request;

class TestRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation messages.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required'    => 'A title is required.',
            'name.required'    => 'The name field is required'
        ];
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required',
            'name' => 'required',
        ];
    }
}

Inject the request object into your controller method.

public function store(TestRequest $request)
{
    // You don't need any validation, this is already done
    test::create($request->all());
}
379

Answer

Solution:

You could also look at validating in your model and throwing a ValidationException which will be handled as usual in your controller (with the error bag etc). E.g:

abstract class BaseModel extends Model implements ModelInterface {
    protected $validationRules = [];

    /**
     * Validate model against rules
     * @param array $rules optional array of validation rules. If not passed will validate against object's current values
     * @throws ValidationException if validation fails. Used for displaying errors in view
     */
    public function validate($rules=[]) {
        if (empty($rules))
            $rules = $this->toArray();

        $validator = \Validator::make($rules,$this->validationRules);
        if ($validator->fails())
            throw new ValidationException($validator);
    }

    /**
     * Attempt to validate input, if successful fill this object
     * @param array $inputArray associative array of values for this object to validate against and fill this object
     * @throws ValidationException if validation fails. Used for displaying errors in view
     */
    public function validateAndFill($inputArray) {
        // must validate input before injecting into model
        $this->validate($inputArray);
        $this->fill($inputArray);
    }
}

Then in my Controller:

public function store(Request $request) {
    $person = $this->personService->create($request->input());

    return redirect()->route('people.index', $person)->with('status', $person->first_name.' has been saved');
}

Finally in my base service class

abstract class BaseResourceService {
    protected $dataService;
    protected $modelClassName;

    /**
     * Create a resource
     * @param array $inputArray of key value pairs of this object to create
     * @returns $object
     */
    public function create($inputArray) {
        try {
            $arr = $inputArray;
            $object = new $this->modelClassName();
            $object->validateAndFill($arr);
            $this->dataService->create($object);
            return $object;
        }
        catch (Exception $exception) {
            $this->handleError($exception);
        }
    }

If the model validates it continues as usual. If there's a validation error it goes back to the previous page with the validation errors in the flash data/error bag.

I will most probably move the $person->validate() method to my service class, however it will still work as outlined above.

166

Answer

Solution:

You can simply make your validation by writing in Model.

In your Model File

i.e. Models\Test.php

public static $createRules = [
   'name'=>'required|max:111',
   'email'=>'required|email|unique:users',
];

In Controller

public function store(Request $request)
{
     $request->validate(ModalName::$createRules);
     $data = new ModelName();
}

Just do this. Everything will be fine.

People are also looking for solutions to the problem: reflection - Php, how to get parameters as a string (as I got?)

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.