Relationship no Laravel

Asked

Viewed 43 times

1

Speak guys, I’m starting to use the Standard and I’m having a problem selecting some data.

I have the following tables: users, jobs, projects, job_user.

  • The list of users and jobs is of many to many and is done through the auxiliary table job_user.
  • A job belongs to a project.

Relations at Model Job:

public function scopeAuthUser($q)
{
    return $q->whereHas('users', function($q){
        $q->where('user_id', auth()->user()->id);
    });
}

public function project()
{
    return $this->belongsTo(Project::class);
}

public function users()
{
    return $this->belongsToMany(User::class);
}

Relations in the Model Project:

public function user()
{
    return $this->belongsTo(User::class);
}

public function jobs()
{
    return $this->hasMany(Job::class);
}

Relations on the Model User:

public function jobs()
{
    return $this->belongsToMany(Job::class);
}

Jobscontroller:

public function index()
{
    $jobs = $this->job->authUser()->with('project.company')->get();

    return view('jobs.index', compact('jobs'));
}

The question is as follows, as I do for Projectscontroller, show only Projects that have Jobs that the user is linked to?

  • 1

    It seems to me you’ve already done it by solving with scope :: $jobs = $this->job->authUser()->with('project.company')->get(); ???

  • It returns me an array of Jobs, that inside each one has a project, I need to bring only the Projects in this query...

  • Pera a little, then it’s bringing properly?.

  • 1

    $jobs = $this->job->authUser()->project ???

  • Yes, actually I was curling up, because doing these validations in a controller was very "disorganized" for me, today I started an ACL course and has cleared up several questions including this, thank you for the answers!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.