Eloquent info Schema Builder Query Scope Relation
Проверка на то, что БД уже есть
if (Schema::hasTable('users'))
{
//
}
$this->belongsToMany('model', 'table_name', 'model_id', 'this_id')
$article->tags()->attach(array) просто добавит новые связи
$article->tags()->dettach(array) удалит связи
$articles->tags()->sync(array) оставит только те связи, что есть в переданном массиве
Если в одном классе несколько полей ссылаются на другой объект, то можно добавить столбец в БД и по нему отбирать соответствующие поля:
public function mugshot() {
return $this->morphOne('Image', 'of')->where('type', 'mugshot');
}
public function photos() {
return $this->morphMany('Image', 'of')->where('type', 'photo');
}
Нужно не забывать сохранять правильно Взято отсюда
У модели
public function scopePublished($query){
$query->where('published_at', '<=', Carbon::now());
}
Использовать: Article::latest()->published()->get();
public function setFieldNameAttribute ($data) {
$this->attributes['name' = Carbon::parse($date);
}
Можно добавить свойство, которого нет в БД, но использовать его как остальные
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
Чтобы свойство появилось при сериализации в JSON или array используется $appends
protected $appends = array('is_admin');
Общий сеттер для всех атрибутов setAttribute
public function setAttribute($key, $value)
{
if(empty($value) && in_array ($key, $this->nullable)) {
$value = null;
}
parent::setAttribute($key,$value);
}
Чтобы Laravel преобразовывал поля дат к объектам Carbon:
protected $dates = ['published_at'];
Красивый вывод даты
$created_at->difforHumans() // => 3 days from now
По умолчанию, считает, что у модели есть created_at и updated_at свойства Чтобы оключить:
public $timestamps = false;
В schema builder
$table->timestamps();
$table->nullableTimestamps();
$table->dropTimestamps();
Чтобы только обновить timestaps поля
$model->touch();
По умолчанию, отсутствует
v5 use Illuminate\Database\Eloquent\SoftDeletes;
v4 use \Illuminate\Database\Eloquent\SoftDeletingTrait;
Схема
$table->softDeletes();
$table->dropSoftDeletes();
static $rules = [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed',
'role_id' => 'required|exists:roles,id'
];