with function in laravel code example
Example 1: laravel wherehas
$users = User::whereHas('posts', function($q){
$q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
Example 2: laravel where has
use Illuminate\Database\Eloquent\Builder;
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
})->get();
$posts = App\Post::whereHas('comments', function (Builder $query) {
$query->where('content', 'like', 'foo%');
}, '>=', 10)->get();
Example 3: one to many laravel
For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}
Example 4: associate laravel
When updating a belongsTo relationship, you may use the associate method. This
method will set the foreign key on the child model:
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
When removing a belongsTo relationship, you may use the dissociate method. This
method will set the relationship foreign key to null:
$user->account()->dissociate();
$user->save();
Example 5: by default null eloquent user data in relationship in laravel 8
{{ $post->author->name or 'No author' }}
public function author()
{
return $this->belongsTo('App\Author')->withDefault();
}
public function author()
{
return $this->belongsTo('App\Author')->withDefault([
'name' => 'Guest Author',
]);
}