Reputation: 2365
I have two tables:
users
{ id, username }
items
{ id, user_id }
In laravel, how would I appropriately return the username on an items permalink?
For example:
item #39 by JohnSmith
I tried the following:
$items = DB::table('items')->where('id', '=', 39)->first();
$username DB::table('users')->where('id', '=', $items->user_id)->first();
item #{{ $items->id }} by {{ $username }}
Upvotes: 0
Views: 43
Reputation: 146191
Create two models in your models
directory:
// User Model (app/models/User.php)
class User Extends Eloquent {
public function items()
{
return $this->hasMany('Item');
}
}
// Item Model (app/models/Item.php)
class Item Extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
Now you may use in your controller, something like this:
$item = Item::with('user')->find(39);
$username = $item->user->username;
Upvotes: 1
Reputation: 2894
If you are using Eloquent Models you could simply do
$item = Item::find(39);
$username = $item->user->username;
This of course requires you to have your relationships defined properly in both the User and Item model.
Upvotes: 1