Reputation: 670
I have Project and Reservations table relationship trying to filter the reservations
by the dates inside the project. But getting the error of
mb_strpos() expects parameter 1 to be string, object given
the nested relation is look like below/
{
"id": 1,
"name": "test",
"reservations": [
{
"id": 1,
"project_id": 1,
"date": "2020-01-13",
}
]
}
The below code isn't working:
$startDate = $request->get("startDate");
$endDate = $request->get("endDate");
return Project::find($id)->with(["reservations", function($query) use ($startDate, $endDate) {
$query->whereBetween('date', [$startDate, $endDate]);
}])->get();
project model
class Project extends Model
{
use HasFactory;
protected $table = 'projects';
protected $guarded = [];
public $with = ["reservations"];
public function reservations() {
return $this->hasMany(Reservation::class);
}
}
and reservations model
class Reservation extends Model
{
use HasFactory;
protected $table = "reservations";
protected $guarded = [];
public function project() {
return $this->belongsTo(Project::class, "project_id", "id");
}
}
Upvotes: 0
Views: 265
Reputation: 15319
You have error in your query.Since you call find()
first then calling with
.Also while using array in with
you must use =>
for callback So it should be like below
$startDate = $request->get("startDate");
$endDate = $request->get("endDate");
return Project::with(["reservations"=>function($query) use ($startDate, $endDate) {
$query->whereBetween('date', [$startDate, $endDate]);
}])->find($id);
Also you can use without array in with method like below
Project::with("reservations",function($query) use ($startDate, $endDate) {
$query->whereBetween('date', [$startDate, $endDate]);
})->find($id);
Upvotes: 1