Method Chaining based on condition

不想你离开。 提交于 2019-12-04 09:59:32

I believe your problem happened because you didn't store back the resulting query after each query builder method call.

$query = User::query();

// Checking for username if exists
if (!empty($username)) {
    $query = $query->where('username', $username);
}

// Check for age if exists
if (isset($age)) {
    $query = $query->where('age', $age);
}

// Ordering
$query = $query->orderBy('reg_date', 'DESC');

// Get the first result
// After this call, it is now an Eloquent model
$user = $query->first();

var_dump($user);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!