Data comparison in laravel

Viewed 1584

I'm beginner in laravel and I'm trying to run comparison queries given in the database. I saved a field date that is implemented by a form together with other fields including the name. I tried to query the name and it works all regularly with this code below.

I would like to retrieve all the rows that have the name variable as the field name that I pass (and here it seems to work) and then only those with the field date that have the specified month at the number that I pass as variable $month. what would be the right form to do this? thanks Piero

public function filterparamenter(){
      $name = request('name');
      $month = request('$month');
      $query = subagente::all();
      $query = $query->where('subagente', $subagente);
      $query = $query->whereMonth('data', $month)->get();   

Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.

1 Answers

Using ::all() returns a Collection, which has a ->where() method, but ->whereMonth() is only available on Eloquent's Builder class. Change your code as follows:

$query = subagente::query();
$query = $query->where('subagente', $subagente);
$query = $query->whereMonth('data', $month)->get();

Or, more compact:

$results = subagente::where("subagente", $subagente)
->whereMonth("data", $month)
-get();

Using ::query() or ::where() to start your query will generate a Builder instance, which you can chain addition clauses (->where(), ->whereMonth(), etc) on before calling ->get() to return a Collection of subagente records.

Side note, should "data" be "date"?

Related