Hobby99
Hobby99

Reputation: 703

Laravel accessing joined table in view

I am joining two tables (companies and users on users.id=companies.user_id), send the data to the controller and then pass it to the view where it tells me that $id is an undefined property referring to the line in the view where it says ($comps->id).

Without a join, this message does not show up and all is fine. Do I have to access the properties differently when having a join?

Model:

public static function companyUser(){
        return DB::table('companies as c')
                ->leftJoin('users', 'c.user_id', '=', 'users.id')
                ->select('users.user_name as uname, c.*')
                ->get();
    }

Controller:

$data['companies'] = Companies::companyUser();
return View::make('admin/companies_view', $data);

View:

<?php if($companies) : ?>
        <?php foreach($companies as $comps) : ?>
        <tr>
            <td class="center"><?php echo $comps->id; ?></td>
            <td><?php echo $comps->company; ?></td>
            <td class="center"><?php echo $comps->uname; ?></td>
            <td class="center"><?php echo $comps->rate; ?></td>
            <td class="center"><?php echo $comps->status; ?></td>
        </tr>
        <?php endforeach; ?>
<?php else : ?>
        <tr>
            <td colspan="8" class="no_results">There are no Users</td>
        </tr>
<?php endif; ?>

Upvotes: 0

Views: 2608

Answers (1)

Joel Hinz
Joel Hinz

Reputation: 25384

I think the error is probably that select() expects each thing you want to get as a separate string. So if you want both the user_name and c.*, you'll need to do this:

->select('users.user_name as uname', 'c.*')

That should hopefully be enough to get it going. :)

Upvotes: 2

Related Questions