0

I have a foreach in my view which displays tasks.

 @foreach($project_item->getVisibleTasks($tasklist->id) as $task)

And in my model I have the following function:

  public function getVisibleTasks($tasklist_id)
  {
    return $this->hasMany('App\Task', 'project_id')->where('tasklist_id', $tasklist_id)->orderBy('order', 'asc');
  }

The function does work when I delete the parameters. (But shows all the results. Because the where clause is deleted). When I pass a static number (for example 1) in my view, it still doesnt work.

How can I make this work?

Regards,

Dylan

Capitano
  • 1
  • 1
  • 7

3 Answers3

0

I'm not sure you can use a where clause when setting an eloquent relationship. The Laravel Eloquent Relationship doc page doesn't say that is possible.

If possible use the code below where you rather use the eloquent query builder;

public function getVisibleTasks($tasklist_id){
    return App\Task::where('id',$this->project_id)->where('tasklist_id',$tasklist_id)->orderBy('order', 'asc')->get();
}
Xixis
  • 881
  • 6
  • 8
  • This doesnt work. I still can't call the function with the parameter from the view. The where clause it self does work. (When I use a static integer, it works). The problem is the foreach in the view. (I think its not possible to pass a parameter into a foreach?). – Capitano Aug 13 '18 at 15:27
  • One option would be to call the function in the controller and pass the return list object to the view or you could use **@php** blade syntax to declare a variable in the view and assign the result of the function so that you only call the variable in the **@foreach** loop – Xixis Aug 13 '18 at 15:36
0

it may not be working because the relationship query is being called inside the relationship, you could create a relationship function and a query function, for example

public functon tasks() {
    return $this->hasMany('App\Task', 'project_id');
}

and then your function will be like this

public function getVisibleTasks($tasklist_id)
  {
    return $this->tasks()->where('tasklist_id', $tasklist_id)->orderBy('order', 'asc');
  }

that way laravel fetch the relationship and then filter it.

See this post

Carlos Salazar
  • 1,818
  • 5
  • 25
  • 48
  • Hi, thanks for your answer. This makes no difference. The issue with the parameter in the foreach still occurs. – Capitano Aug 13 '18 at 15:28
0

This seems odd to me, it looks as though you are defining a relationship and running the query where the relationship is defined. you should first define the relationship in the project_item model

 public function getVisibleTasks()
      {
        return $this->hasMany('App\Task', 'project_id');
      }

Also define the inverse of that relationship.

Then call it from your controller via

$project_item ->getVisibleTasks()->orderBy('order', 'asc'); this will automatically call the data that is related to your model.

Yeeooow
  • 188
  • 7