laravel eloquent with function code example
Example 1: 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 2: laravel eloquent associate
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();
Example 3: laravel create on model
$user = User::create([
'first_name' => 'Taylor',
'last_name' => 'Otwell',
'title' => 'Developer',
]);
$user->title = 'Painter';
$user->isDirty();
$user->isDirty('title');
$user->isDirty('first_name');
$user->isClean();
$user->isClean('title');
$user->isClean('first_name');
$user->save();
$user->isDirty();
$user->isClean();
Example 4: laravel belongs to
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User');
}
}
Example 5: laravel how to query belongsTo relationship
$movies = Movie::whereHas('director', function($q) {
$q->where('name', 'great');
})->get();