katie hudson
katie hudson

Reputation: 2893

Accessing data in second table

I am retrieving a list of projects like so

$projects = Project::select('id', 'projectnName', 'projectContact', 'deploymentDate')->get();

In the select part, I could add client_id which will return the id of the client. However, this is linked to an id in my clients table, and I want to select the clients name. I have been trying the following before the select

join('clients', 'clients.id', '=', 'projects.client_id')

But that seems to fail. How can I access the clientName via the client_id?

Thanks

Upvotes: 0

Views: 28

Answers (2)

Steve Bauman
Steve Bauman

Reputation: 8688

Laravel relationships are great for easily doing this.

You should create a Client model in your app directory:

namespace App;

class Client extends Eloquent
{
    //
}

Then, in your Project model, define a client() method:

class Project extends Eloquent
{
    public function client()
    {
        return $this->belongsTo(Client::class);
    }
}

Then, when you query your Project model:

public function index()
{
    $projects = Project::with('client')->get();

    foreach ($projects as $project) {

        // Retrieve the client name of the project:

        $client = $project->client->clientName;

    }
}

Upvotes: 1

SteD
SteD

Reputation: 14025

Add clients.name (table_name.column_name) in your select statement like below:

$projects = Project::select('clients.name','clients.id', 'projectnName', 'projectContact', 'deploymentDate') 
->join('clients', 'clients.id', '=', 'projects.client_id')
->get();

Upvotes: 1

Related Questions