Reputation: 12598
I have a blade template in a Laravel 5.5 app that is returning a user ID integer
I am looking for a way to get the users name from that value within the blade template
The value is just saved in the table and there is no relationship setup, is there a way to get the username without having to set up a relationship?
** UPDATE **
My products controller looks like this...
public function index()
{
$users = User::all();
$products= Product::all();
return view('products.index',compact('products', 'users'));
}
So now I have the users available inside the blade template but now I need to get the user from the id that is contained in produts
Upvotes: 1
Views: 6966
Reputation: 8047
In your controller that's passing the user data to the view, you can either pass the entire $user
object and print it in your view like {{ $user->name }}
or set yourself a variable that holds just the username and pass that in for however you're using it.
I would do the first one though, something like:
public function index()
{
$user = User::where('id',$id)->firstOrFail();
return view('dashboard.index', compact('user'));
}
Or if you're getting all users from the database, an example would be:
public function index()
{
$users = User::all();
return view('dashboard.index', compact('users'));
}
Then in your view you can do
@foreach($users as $user)
{{ $user->name }}
@endforeach
Edit
Since seeing your updated question, you would benefit from making a relationship between your users
and your products
. So, you would say that a user has many products
and that a product belongs to a user
.
class User extends Model
{
/**
* Get all of the products for the user.
*/
public function products()
{
return $this->hasMany('App\Product');
}
}
And then
class Product extends Model
{
/**
* Get the user that is assigned to the product
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
Once you have set this up, you can loop through your products and get the username like this:
@foreach($products as $product)
{{ $product->user->name }}
@endforeach
Upvotes: 3
Reputation: 7128
Auth::user()->name
if user is online. if not you must have controller function like:
$users = User::all();
and in blade
@foerach($users as $user)
{{$user->name}}
@endforeach
Upvotes: 0
Reputation: 2353
Create helper file: follow this rule to make it : https://laravel-news.com/creating-helpers
and make one function like this:
function getUsername($uerId) {
return \DB::table('users')->where('user_id', $userId)->first()->name;
}
and call this function from your view like this :
{{getUsername($id))}} //it will print user name;
Upvotes: 3