You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Post extends Eloquent
{
publicstaic$autoValidates = true;
protectedstatic$rules = [];
protectedstaticfunctionboot()
{
parent::boot();
// or static::creating, or static::updatingstatic::saving(function($model)
{
if ($model::$autoValidates) {
return$model->validate();
}
});
}
publicfunctionvalidate()
{
}
}
2. Prevent updating
class Post extends Eloquent
{
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
return false;
});
}
}
3. Conditional Relationships
class myModel extends Model
{
public function category()
{
return $this->belongsTo('myCategoryModel', 'categories_id')
->where('users_id', Auth::user()->id);
}
}
SELECT *, COUNT(*) FROM products GROUP BY category_id HAVING count(*) > 1;
DB::table('products')
->select('*', DB::raw('COUNT(*) as products_count'))
->groupBy('category_id')
->having('products_count', '>', 1)
->get();
use Ramsey\Uuid\Uuid;
trait UUIDModel
{
public $incrementing = false;
protected static function boot()
{
parent::boot();
static::creating(function ($model)
{
$key = $model->getKeyName();
if (empty($model->{$key})) {
$model->{$key} = (string) $model->generateNewId();
}
});
}
public function generateNewUuid()
{
return Uuid::uuid4();
}
}
11. Ordered Relationships
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product')->orderBy('name');
}
}
12. Simple Incrementing & Decrementing
$customer = Customer::find($customer_id);
$loyalty_points = $customer->loyalty_points + 50;
$customer->update(['loyalty_points' => $loyalty_points]);
// adds one loyalty point
Customer::find($customer_id)->increment('loyalty_points', 50);
// subtracts one loyalty point
Customer::find($customer_id)->decrement('loyalty_points', 50);
13. Lists with Mutations
// TODO
14. Appending Mutated Properties
// TODO
15. Filter only rows with child rows
class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product');
}
}
public function getIndex()
{
$categories = Category::with('products')->has('products')->get();
return view('categories.index', compact('categories'));
}
16. Return relations on model save
public function store()
{
$post = new Post;
$post->fill(Input::all());
$post->user_id = Auth::user()->user_id;
$post->user;
return $post->save();
}