- https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes
- https://www.reddit.com/r/laravel/comments/3to60i/50_laravel_tricks/
class Post extends Eloquent
{
public staic $autoValidates = true;
protected static $rules = [];
protected static function boot()
{
parent::boot();
// or static::creating, or static::updating
static::saving(function($model)
{
if ($model::$autoValidates) {
return $model->validate();
}
});
}
public function validate()
{
}
}class Post extends Eloquent
{
protected static function boot()
{
parent::boot();
static::updating(function($model)
{
return false;
});
}
}class myModel extends Model
{
public function category()
{
return $this->belongsTo('myCategoryModel', 'categories_id')
->where('users_id', Auth::user()->id);
}
}$products = Product::where('category', '=', 3)->get();
$products = Product::where('category', 3)->get();
$products = Product::whereCategory(3)->get();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();$q->whereDate('created_at', date('Y-m-d'));
$q->whereDay('created_at', date('d'));
$q->whereMonth('created_at', date('m'));
$q->whereYear('created_at', date('Y'));// src/Illuminate/Database/Eloquent/Model.php
public function save(array $options = [])
// src/Illuminate/Database/Eloquent/Model.php
protected function performUpdate(Builder $query, array $options=[])
{
if ($this->timestamps && array_get($options, 'timestamps', true))
{
$this->updateTimestamps();
}
}
$product = Product::find($id);
$product->updated_at = '2015-01-01 00:00:00';
$product->save(['timestamps'=>false]);// TODO$questions = Question::orderByRaw('RAND()')->take(10)->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();
}
}class Category extends Model
{
public function products()
{
return $this->hasMany('App\Product')->orderBy('name');
}
}$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);// TODO// TODOclass 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'));
}public function store()
{
$post = new Post;
$post->fill(Input::all());
$post->user_id = Auth::user()->user_id;
$post->user;
return $post->save();
}$devs = [
['name' => 'Anouar Abdessalam', 'email' => '[email protected]'],
['name' => 'Bilal Ararou', 'email' => '[email protected]'],
];
$devs = new \Illuminate\Support\Collection($devs);Keeps the item only if the closure returns true
$customers = Customer::all();
$us_customers = $customers->filter(function($customer)
{
return $customer->country == 'United States';
});// returns a single row as a collection
$collection = Person::find([1]);
// returns multiple rows as a collection
$collection = Person::find([1, 2, 3]);$collection = Person::all();
$programmers = $collection->where('type', 'programmer');$collection = Person::all();
$names = $collection->implode('first_name', ',');// returns a collection of first names
$collection = Person::all()->where('type', 'engineer')->lists('first_name');
// returns all meta records for user 1
$collection = WP_Meta::whereUserId(1)->get();
// returns first name meta values
$first_name = $collection->where('meta_key', 'first_name')->lists('value')[0];class Link extends Model
{
public function users()
{
return $this->belongsToMany('Phpleaks\User')->withTimestamps();
}
}
@if ($link->users->count() > 0)
<strong>Recently Favorited By</strong>
@foreach ($link->users()->orderBy('link_user.created_at', 'desc')->take(15)->get() as $user)
...
@endforeach
@endif$sorted = $collection->sortBy(function($product, $key)
{
return array_search($product['name'], [1=>'Bookcase', 2=>'Desk', 3=>'Chair']);
});Defines the 'key' for an array-as-collection (for use with e.g. ->contains)
$library = $books->keyBy('title');$collection = Person::all();
$grouped = $collection->groupBy('type');// the point is to actually combine results from different models
$collection = new Collection;
$all = $collection->merge($programmers)->merge($critics)->merge($engineers);$collection = collect([1=>11, 5=>13, 12=>14, 21=>15])->getCachingIterator();
foreach ($collection as $key=>$value)
{
dump ($collection->current() . ':' . $collection->getInnerIterator()->current());
}