【发布时间】:2017-07-09 07:53:25
【问题描述】:
我正在使用基于 Laravel 的 OctoberCMS。
我正在尝试从 URL 中获取标识符并将其传递给 Scope 以过滤数据库结果。
$this->property('username') 有效并从 URL 返回用户名。
但是如何将它传递给 Model 和 Scope 函数呢?
这是动态范围下的指南。
https://octobercms.com/docs/database/model#query-scopes
页面
网址:localhost/user/matt
标识符:/user/:用户名
结果组件
public function init()
{
// get username from url
$username = $this->property('username'); //matt
// pass username to scope
Gallery::applyUser($username);
}
画廊模型
// return results that match username
public function scopeApplyUser($query, $username)
{
return $query->where('username', $username);
}
错误
Missing argument 2 for MyVendor\Gallery\Models\Gallery::scopeApplyUser()
解决方案?
我发现添加 ($query, $username = null) 允许变量无错误地传递。
但现在的问题是 $username 同时是 'matt' 和 null 并且永远不会返回查询。
// return results that match username
public function scopeApplyUser($query, $username = null)
{
print $username; //prints matt
if ($username == null) { print 'null'; } //prints null
return $query->where('username', $username); //returns null
}
【问题讨论】:
-
尝试使用如下方式从 url 获取属性 $username = $_GET['username'];而不是 $username = $this->property('username');你会知道真正的财产是可以访问的。
-
旁注:也可以尝试使用
Input::get("url_param") -
@Meysam 它返回 null。
标签: php laravel laravel-5 octobercms