Get username from ID - laravel

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

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

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;

{{\App\User::findOrFail($id)->name}}

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

Related

fetching data through model binding relationship in laravel

I was trying to get the user's photo src which is stored in the photos table and the photo id is stored in the users' table. My code -
I've written these lines in my User Model
Model - User
public function photo() {
return $this->belongsTo(Photo::class);
}
and my code for printing the photo src -
Route::get("/photo",function() {
$users = User::all();
foreach($users as $user) {
echo $user->photo->file . "<br>";
}
});
It shows an error saying -
Trying to get property 'file' of non-object
On the other hand, I have the same relationship binding which works fine -
In the User Model -
public function role() {
return $this->belongsTo(Role::class);
}
and for printing the role name of the user -
Route::get("/photo",function() {
$users = User::all();
foreach($users as $user) {
echo $user->role->name . "<br>";
}
});
so if the role name is printing by this way why the photo src is not printing
When you're using a Model relationship then you need to do it by calling it in your User::all()->with() method.
Whatever your relation may be it will be it's name will be called inside with() method in order to properly get the required data.
considering the relation ship is done properly you can do it like following:
Model User has the following relation with photos:
public function photo() {
return $this->hasMany(Photo::class);
}
Model Photo has the following relation with User.
public function user(){
return $this->belongsTo(User::class);
}
After this, you can call it inside your Controller
public function get_photo(){
$users = User::all()->with('photo');
return view('example.blade.php,compact('users'));
}
Routes
Route::get('/photo',[Controller::class,'get_photo'])->name('get.photo');
View
Your view can have the foreach loop to iterate through photos
foreach($users as $user) {
echo $user->photo->file . "<br>";
}

Fetching data from two tables in Laravel in show function in controller?

I have two Model, School, and Student the relationship is, School has Many Student
//Student Model
public function school()
{
return $this->belongsTo('App\School');
}
and same in School Model the following is the function for relationship
public function student()
{
return $this->hasMany('App\Student');
}
Now I have a show Page I like to display the following information. (school_name,school_code) from the school table and student information all from the Student Table.using show function in student controller if I pass as
public function show($id)
{
$student=Student::find($id);
$school=School::find($id);
return View::make('student.show')->with(['school'=> $school,'student'=>$student]);
}
it gets data from school if school_id ==$id but one school has many students it fails if I click to show a button with an ID of 109, how to write the Join query to get school_code and school_name from schools table.
Not sure why you are using the same $id to getting student and school
public function show($id)
{
$student = Student::find($id);
$school = $student->school; //school of the student
return View::make('student.show')->with(['school'=> $school,'student'=>$student]);
}
Use this code
Your model should be like this
public function students()
{
return $this->hasMany('App\Student');
}
You have to change like this.
$student = Student::find($id);
$school = $student->school;
Since you have the relationship setup already, you could use Eloquent to fetch data for single student with the school that he belongs tos as follow:
public function show($id)
{
$student = Student::with('school')->where('id', $id)->first();
return View::make('student.show')->compact('student);
}
Now you can retrieve data show.blade.php as follow:
#foreach($student as $stud)
<li> {{ $stud->student_name}}</li>
<li> {{ $stud->student_code}}</li>
<li> {{ $stud->->school->school->name}}</li>
<li> {{ $stud->school->school_name }}</li>
#ndforeach

one to may relationship, Display all post along with there users

//Post table
user()
`belongsTo(User::class);`
//user table
posts()
hasMany(post::class);
//I want to get all the post available in the DB, Display along with the users associated with the post.
Use foreign key and primary key in relationships to get the results.
In Post
public function user()
{
return $this->belongsTo('App\User','users_id','users_id') //first parameter-foreign key,second parameter-local key
}
In User
public function posts()
{
return $this->hasMany('App\Post','users_id','users_id')
}
Now get all the posts using
$posts = Post::get();
return view('your-view')->with('posts',$posts);
You can retrieve user information in view using
#foreach($posts as $post)
$user = $post->user->name;
#endforeach
Hope it helps..
Guessing your relations look like this:
User:
public function posts()
{
return $this->hasMany('App\Post');
}
Post:
public function user()
{
return $this->belongsTo('App\User')
}
You could get all the posts in your controller, like this:
$posts = Post::get();
return view('your view', $posts);
And in your blade, to display posts and their users, do it like this:
#foreach($posts as $post)
$post->user->name
#endforeach
$posts = Post::with('user')->get();

How to use index method to display a listing of the resource in Laravel

I created a customerController with Laravel resource. Now I want to show the list of the customers from the database using the index() method and it doesn't work when I visit the customer/index route. However if use the show() method instead and visit the customer/show route, it works perfectly.
Why does this behave this way and how do I get the index() method to do this?
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return view('customer')->with('customers' , $customers);
}
public function show($id)
{
// adding the code in the index() method here makes the code run
// as expected
}
}
customer.blade.php
<ul>
#foreach($customers as $customer)
<li>{{$customer->name}}</li>
#endforeach
</ul>
routes/web.php
Route::resource('customer' , 'CustomerController');
I expect the output to be:
.sucre
.hameed
.micheal
I just learned how to use resource on Laravel 8.
Which version are you using?
Run php artisan route:list on your console to see every route available and their names.
To see all customers through your index function do the following:
public function index()
{
$customers = Customer::all();
return view('customer', [
'customers' => $customers
]);
}
Now just access your customer.blade.php file on browser.
PS: Don't forget of #foreach
#foreach ($customers as $customer)
{{ $customer->attribute }}
#endforeach
Hope this could be useful.

query builder returns array instead of collection

User.php(User model)
class User extends Authenticatable
{
public function profiles(){
return $this->hasOne('App\Profile');
}
}
Profile.php (Profile model)
class Profile extends Model
{
public function users(){
return $this->belongsTo('App\User');
}
}
Function which returns data to view:
public function show_users(){
$users = User::where('id','!=',Auth::user()->id)->get();
return view('pages.show_users')->withUsers($users);
}
show_user.blade.php(View)
#foreach($users as $user)
{{$user->profile->first_name}} //Gives error:Trying to get property of non-object
{{$user->profiles['first_name']}} // Gives desired result
#endforeach
Why the result is returned in array instead of collection?
The reason that you are getting that error is beacause
Some users might not have a profile. so calling first_name on profile which is a null object will throw an error.
What you can is on php7 you can do
#foreach($users as $user)
{{$user->profiles->first_name ?? 'No first name'}}
#endforeach
php 5.6 and below
#foreach($users as $user)
#if($user->profiles->isNotEmpty())
{{$user->profiles->first_name}}
#else
No name
#endif
#endforeach
And moreover why don't use eager loading to load your profiles for performance benefit. Your query now will create the N+1 query problem.
You can change your query to
public function show_users()
{
$users = User::with('profiles')->where('id','!=',Auth::user()->id)->get();
return view('pages.show_users')->withUsers($users);
}
Hope it helps
The result returned is indeed a collection. It is just a typo issue
You forget an s here in profiles
{{ $user->profiles->first_name }}
Also please note that even if you access first_name as such
{{ $user->profiles['first_name'] }}
It doesn't mean it is not a collection.
If you check the source of Illuminate\Database\Eloquent\Model.php, you will see that it implements some cool functions such as offsetGet, offsetSet, and offsetExists
More information here. PHP ArrayAccess

Resources