I'm using OctoberCMS based on Laravel.
I'm trying to get the identifier from URL and pass it to the Scope to filter database results.
$this->property('username') works and returns the username from the URL.
But how do you pass it to the Model and into the Scope function?
Here is the guide, under Dynamic Scopes.
https://octobercms.com/docs/database/model#query-scopes
Page
URL: localhost/user/matt
Identifier: /user/:username
Results Component
public function init()
{
// get username from url
$username = $this->property('username'); //matt
// pass username to scope
Gallery::applyUser($username);
}
Gallery Model
// return results that match username
public function scopeApplyUser($query, $username)
{
return $query->where('username', $username);
}
Error
Missing argument 2 for MyVendor\Gallery\Models\Gallery::scopeApplyUser()
Solution?
I found adding ($query, $username = null) allows the variable to pass without error.
But now the problem is that $username is both 'matt' and null at the same time and never makes it to the query return.
// 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
}
In a model gallery you need a field user:
Then, when you have the nullchecks you can just call it with
Changes I made:
full working example that prints the results: