I am new to Laravel. Now I am starting to develop a project using Laravel 5. I have been using CodeIgniter before. I am having problem with validation class that is not compatible with what I want to do.
Normally we validate in Controller like this.
public function postCreate(Request $request)
{
$this->validate($request, [
'name' => 'required|max:30',
'mm_name' => 'required|max:50',
]);
echo "passed";
}
That is working find. But what I want to do is I want to move that validation logic to model. So I created a new folder called Models under app folder. Under the Models folder I created a class called ValidationHelper that extends the Model class.
This is my Validation helper class
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class ValidationHelper extends Model{
function CreateCategory($request)
{
$this->validate($request, [
'name' => 'required|max:30',
'mm_name' => 'required|max:50',
]);
}
}
So now I am trying to import that class to my controller using constructor dependency injection. So now my controller is like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\ValidationHelper;
class CategoryController extends Controller
{
protected $validationHelper;
function __construct(ValidationHelper $v_helper)
{
$this->validationHelper = $v_helper;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function categoryList()
{
//
return View('admin.Category.list');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return View('admin.Category.create');
}
}
So when I run my app and do validation, it is giving me this error. How can I do this in Laravel? How to separate my validation logic to model?
You can move the code in your model by registering model event(s) as given below:
// For example, User.php model
public static function boot()
{
parent::boot();
static::creating(function($user)
{
if (!$user->isValid()) return false;
}
}
If you put this boot
method in your User.php
model then whenever you'll create a new user, the validation will take place at first. For this, you have to create the isValid
method in your model where you'll check the validation by yourself and return true/false depending on the validation result. If you return false, creation will be inturupted. This is just an idea but you may read more here about model events.