S.M_Emamian S.M_Emamian - 4 months ago 8
PHP Question

how to use a simple Relationships in laravel

I have two tables like below:

users
table:

id - fname - lname


users_projects
table:

id - user_id - title


my models are inside a directory called
Models
:

Users
model :



namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Users extends Model
{
//

public function usersProjects()
{
return $this->belongsTo(UsersProjects::class);
}
}


UsersProjects
model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UsersProjects extends Model
{
protected $table = 'users_projects';
//

public function users()
{
return $this->hasOne(Users::class);
}
}


now, I want to show last projects :

$projects = UsersProjects::limit(10)->offset(0)->get();

var_dump($projects);
return;


but my
var_dump
shows last projects ! I want to have
fname
and
lname
! where is my wrong ?

Answer

I think you may have your relationships set up a little wrong. If a user can have more than one project, in your user model ...

public function usersProjects()
{
    return $this->hasMany(UsersProjects::class);
}

You might want to use a little simpler naming too ...

public function Projects()
{
    return $this->hasMany(UserProject::class);
}

(or simply Project if you don't have any other "Project" models)

The in your "Project" class ...

public function User()
{
    return $this->belongsTo(User::class);
}

(assuming you rename your model to User instead of "Users". Your table name should be "users" but a model is by nature a singular object. So it's appropriate to call it "User" - and your UsersProjects model should just be UserProject or just Project)

Now if you call the method something other than "User" you will have to add the foreign key name ...

public function SomeOtherName()
{
    return $this->belongsTo(User::class, 'user_id');
}

Then ...

$projects = Project::with('User')->limit(10)->offset(0)->get();

Will return a collection of projects with the User eager-loaded. (assuming you have renamed your UsersProjects model to "Project")

@foreach($projects as $project)
    ...
    First Name: {{ $project->User->fname }}
    ...
@endforeach
Comments