Moussa Chaabar
Moussa Chaabar

Reputation: 501

Laravel 5.1 Select user of a project post with a foreign key

We are building an application for school where users can upload projects. I have a page with all the projects that are uploaded displayed on it. But I want to show the uploader of the project aswell.

My Project model:

class Project extends Model
{
   protected $fillable = [
   'title',
   'tags',
   'summary',
   'published_at'
 ];
}

My User model:

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

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

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

My migration create_projects_table

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('title');
        $table->string('tags');
        $table->string('summary');
        $table->string('file_name');
        $table->timestamp('published_at');
        $table->timestamps(); 
        $table->softDeletes();
    });
}

My view, and how I display all the projects:

@foreach ($projects as $project)
<article>
    <h2><a href="projects/{{ $project->id }}">{{ $project->title }}</a></h2>
    <span>{{ $project->tags }}</span><br/>
    <img src="uploads/projects/{{ $project->file_name }}">
</article>
@endforeach

So in the article I would like to add somehting like "Uploaded by: username". How can I select the username from the users table with the foreign key in my projects table?

Upvotes: 1

Views: 123

Answers (1)

Peter Kota
Peter Kota

Reputation: 8340

Project model:

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

Add to your view the $projects variable and try it:

@foreach($projects as $project)
{
    <article>
        <h2><a href="projects/{{ $project->id }}">{{ $project->title }}</a></h2>
        <span>{{ $project->tags }}</span><br/>
        <img src="uploads/projects/{{ $project->file_name }}">
        <p>Uploaded by: {{ $project->user->name }}</p>
    </article>
}

Upvotes: 1

Related Questions