vendredi 11 décembre 2015

How to validate in model in laravel 5?

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 compitable with whatI want to do. Please see my scenario below.

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

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. So please how can I do this in laravel ?How to seperate my validation logic to model? Please help me.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire