Ehsan
Ehsan

Reputation: 459

laravel use field in Eloquent model from another table

I have a model named "User". I want "Password" field from Eloquent from another table, and when user calls the user::all() method, all selected fields from different tables come in the result. How can i do that?

Results are not displayed in with() .

Upvotes: 2

Views: 2191

Answers (2)

Ehsan
Ehsan

Reputation: 459

my problem solved by using $appends in Eloquent model .

my code :

class User extends Eloquent {
protected $table = 'user';
protected $attributes = ['password'];
protected $appends = ['password'];
public function getPasswordAttribute()
{
    return $this->getPAsswordMethod();  
}
}

Upvotes: 4

ExohJosh
ExohJosh

Reputation: 1892

Your question is extremely board and borderline unanswerable but I will give you a board solution.

You are able to establish relationships to other tables via the Model objects you create. Lets pretend you have a Password table which belongs to the User.

User model:

public function password()
{
return $this->hasOne(Password::class, 'FK', 'PK');
}

You can now do User::with('password')->get(['FieldName']); and this will give you all of the passwords which have the above relationship to a user.

Upvotes: 3

Related Questions