Skip to content
Advertisement

Laravel collection how to return where no records and not by auth user

public function tasks(Request $request)
{
    $user = auth::user();
    $query = Task::query();

    $query->with('User')->with('task_type');
    $q = $query->paginate($tasksPerPage);

    foreach ($q as $task) {
        $status = Join::where('user_id', $user->id)->where('task_id', $task->id)->first();
        if ($status['user_id'] === $user->id) {
            $task->current_status = false;
        } else {
            $task->current_status = true;
        }
    }

    return $q;
}

How can I return only a task, not by user auth wherein the join no records and not by auth user? How can I only return tasks of an unauthorized user and where there are no records in another table join?

Task.php

    public $primaryKey = 'id';
    public $timestamps = true;
    protected $table = 'tasks';
    protected $attributes = ['current_status' => 0];
    protected $visible = ['id', 'name', 'description','user_id', 'task_type_id', 'User','joined','task_type','current_status'];

    public function user()
    {
        return $this->belongsTo('AppUser');
    }

    public function task_type()
    {
        return $this->hasOne('AppTaskType', 'id', 'task_type_id');
    }

    public function joined()
    {
        return $this->hasManyThrough('AppJoin', 'AppTask', 'id', 'task_id', 'id', 'id');
    }

Join.php

    public function task()
    {
        return $this->belongsToMany('AppTask', 'join_task');
    }
        public function user_join()
    {
        return $this->belongsTo('AppUser', 'user_id', 'id');
    }

Advertisement

Answer

Solution is

Task.php

    public function join()
    {
        return $this->hasOne('AppJoin','task_id');
    }

TaskController.php

 $user = Auth::user();
 $query->where('user_id', '!=', $user->id)
                ->WhereDoesntHave('join', function (Builder $query) use($user){
                $query->where('user_id', 'like', $user->id);
            });
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement