- vừa được xem lúc

20 tips xử lý dữ liệu với Eloquent trong laravel

0 0 19

Người đăng: Trường Trần Văn

Theo Viblo Asia

1. Increments and Decrements

Article::find($article_id)->increment('read_count');
Article::find($article_id)->increment('read_count', 10); // +10
Product::find($produce_id)->decrement('stock'); // -1

2. XorY methods

findOrFail

$user = User::findOrFail($id);

firstOrCreate()

$user = User::firstOrCreate(['email' => $email]);

3.Model boot() method

public static function boot() { parent::boot(); static::saving(function ($model) { // do some logging // override some property like $model->something = transform($something); }); static::updating(function($model) { // do some logging // override some property like $model->something = transform($something); }); static::deleting(function($model) { // do some logging // override some property like $model->something = transform($something); }); }

4.Relationship with conditions and ordering

public function approvedUsers() { return $this->hasMany('App\User')->where('approved', 1)->orderBy('email');
}

5.Model properties: timestamps, appends etc.

class User extends Model { protected $connection = 'connection-name'; protected $table = 'users'; protected $guarded = 'user'; protected $fillable = ['email', 'password']; // which fields can be filled with User::create() protected $dates = ['created_at', 'deleted_at']; // which fields will be Carbon-ized protected $appends = ['field1', 'field2']; // additional values returned in JSON protected $primaryKey = 'uuid'; // it doesn't have to be "id" public $incrementing = false; // and it doesn't even have to be auto-incrementing! protected $perPage = 25; // Yes, you can override pagination count PER MODEL (default 15) const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; // Yes, even those names can be overridden public $timestamps = false; // or even not used at all
}

6. Find multiple entries

$users = User::find([1,2,3]);

7. WhereX

$users = User::whereApproved(1)->get(); User::whereDate('created_at', date('Y-m-d')); User::whereDay('created_at', date('d')); User::whereMonth('created_at', date('m')); User::whereYear('created_at', date('Y'));

8. Load

$order = $order->load(['order_info', 'products:id,title','order_address' => function ($query){ $query->with('province', 'district', 'ward'); }]);

9. Eloquent::when() – no more if-else’s

$query = Author::query();
$query->when(request('filter_by') == 'likes', function ($q) { return $q->where('likes', '>', request('likes_amount', 0));
});
$query->when(request('filter_by') == 'date', function ($q) { return $q->orderBy('created_at', request('ordering_rule', 'desc'));
});

10. BelongsTo Default Models

{{ $post->author->name ?? '' }} or {{ optional($post->author)->name }}

11. Order by Mutator

Trong model bạn thêm function:

function getFullNameAttribute()
{ return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}

Cách sắp xếp:

$clients = Client::get()->sortBy('full_name');

12. Default ordering in global scope

protected static function boot()
{ parent::boot(); // Order by name ASC static::addGlobalScope('order', function (Builder $builder) { $builder->orderBy('name', 'asc'); });
}

13. Raw query methods

// whereRaw
$orders = DB::table('orders') ->whereRaw('price > IF(state = "TX", ?, 100)', [200]) ->get(); // havingRaw
Product::groupBy('category_id')->havingRaw('COUNT(*) > 1')->get(); // orderByRaw
User::where('created_at', '>', '2016-01-01') ->orderByRaw('(updated_at - created_at) desc') ->get();

14. Replicate: make a copy of a row

$task = Tasks::find(1);
$newTask = $task->replicate();
$newTask->save();

15.Chunk() method for big tables

User::chunk(100, function ($users) { foreach ($users as $user) { // ... }
});

16.Create additional things when creating a model

php artisan make:model Company -mcr

  • -m tương ứng là sẽ tao ra file migration
  • -c tương ứng là sẽ tạo file Controller
  • -r tương là sẽ biểu thị rằng Controller được tạo ra là Resource Controller

17.Override updated_at when saving

$product = Product::find($id);
$product->updated_at = '2019-01-01 10:00:00';
$product->save(['timestamps' => false]);

18.What is the result of an update()?

$result = $products->whereNull('category_id')->update(['category_id' => 2]);

19. Transform brackets into an Eloquent query

$q->where(function ($query) { $query->where('gender', 'Male') ->where('age', '>=', 18);
})->orWhere(function($query) { $query->where('gender', 'Female') ->where('age', '>=', 65); })

20. orWhere with multiple parameters

$q->where('a', 1);
$q->orWhere(['b' => 2, 'c' => 3]);

Chúc các bạn thành công !

Bình luận

Bài viết tương tự

- vừa được xem lúc

Laravel Best Practices - Code laravel thế nào cho chuẩn (P1)

1. Nguyên tắc ĐƠN TRÁCH NHIỆM - Single responsibility principle. Một lớp hay class chỉ nên có 1 trách nhiệm duy nhất. Đây là 1 trong các nguyên tắc của SOLID.

0 0 21

- vừa được xem lúc

Tips & best practices for Laravel 8

Hế lô các bạn ^^. Hôm nay mình sẽ chỉ cho bạn vài thủ thuật có thể nó sẽ giúp ích cho bạn khi viết code sử dụng Frameword Laravel nhé.

0 0 24

- vừa được xem lúc

WhereHas và With trong laravel

Hôm nay chúng ta cùng tìm hiểu WhereHas và With trong laravel nhé^^. Có thể bạn đã biết với Eloquent relationships mặc định thì access đến data trong Eloquent sẽ dùng"lazy loaded".

0 0 114

- vừa được xem lúc

Sử dụng Laravel Eloquent withSum() and withCount()

Bài viết này mình sẽ giới thiệu các bạn cách sử dụng withSum() and withCount() với laravel relationship eloquent. Bạn có thể sử dụng withSum() & withCount() với laravel 6, laravel 7 & laravel 8 versio

0 0 60

- vừa được xem lúc

Hướng dẫn nén ảnh bằng TinyPNG Laravel PHP

Hi mọi người. Trước m lên diễn đàn Free Tuts gì đó hỏi nhưng ông chủ kênh thì nói cái này khó rồi này nọ, ghét cái thái độ (hơi nói xấu nhưng lỡ nói thì nói luôn).

0 0 22