Return to site
· Laravel,Web,Web Development,Eloquent,tips
broken image

1. Automatic Model Validation

It can sometimes be convenient to automatically validate your model when it gets created or updated. This is very easily achieved with Laravel through the use of Model events.class Post extends Eloquent

    public staic $autoValidates = true;

    protected static $rules = [];

    {

        parent::boot();

        static::saving(function($model)

        {

            if ($model::$autoValidates) {

                return $model->validate();

            }

        });

    }

    public function validate()

    {

    }

}

2. Prevent updating

{

    protected static function boot()

    {

        parent::boot();

        static::updating(function($model)

        {

            return false;

        });

    }

}

3. Conditional Relationships

{

    public function category()

    {

        return $this->belongsTo('myCategoryModel', 'categories_id')

            ->where('users_id', Auth::user()->id);

    }