Cruzito Cruzito - 5 months ago 15
SQL Question

Laravel getting data from other table in view when you know the id

I have a table "reviews" with a column named "from_user". So basically the user who placed the review. In this column the users's id is stored from the users table. Is it possible to find out the users name in my view?

This is what it looks like now:

@foreach($authUser->reviews as $review)
<p>{{ $review->body }} - {{$review->from_user }}</p>
@endforeach


So this code now obviously displays the id of the user.

This is what my users table looks like:


ID | NAME | USERNAME | ...


This is what my reviews table looks like:


ID | from_user | on_user | body


so the from_user from my reviews table equals the ID of my users table

So my question is is it possible to access my username in my foreach loop in my view?

I am fairly new to laraval so any help is appreciated!

Many thanks in advance

EDIT: User Model



class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, Messagable;

protected $table = 'users';

protected $fillable = ['name', 'email', 'password', 'firstname', 'lastname', 'straat', 'postcode', 'plaats', 'provincie', 'role', 'specialisatie'];

protected $hidden = ['password', 'remember_token'];

public function projects()
{
return $this->hasMany('App\Project');
}

public function reviews()
{
return $this->hasMany('App\Review');
}

public function comments()
{
return $this->hasMany('App\Comment');
}
}


EDIT2 my Review model



<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
protected $guarded = [];

protected $table = 'reviews';

public function User()
{
return $this->belongsTo('App\User');
}
}

Answer

Updated

In your review model you need to tell the relation what foreign key to use. By default it add relationName_id.

Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method. #Source

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
    protected $guarded = [];

    protected $table = 'reviews';

    public function user()
    {
       return $this->belongsTo('App\User', 'from_user');
    }
}

And in your view

@foreach($authUser->reviews as $review)
   <p>{{ $review->body }} - {{ $review->user->name }}</p>
 @endforeach
Comments