S
S
Stanislav Pochepko2016-05-30 18:13:09
MySQL
Stanislav Pochepko, 2016-05-30 18:13:09

How to add calculated field to eloquent selection in Laravel?

Good evening. Tricky question. How to make that during selection of the list of models by a method The connected User models had a field which is calculated during selection. That is, somehow assign a method to it. This is necessary to search for the associated model by user name.
$Projects = Project::with('user')->all();
selectRaw("CONCAT(f_name, f_name) as name")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2016-06-02
@DJZT

$projects = Project::with(['user' => function ($query) {
    return $query->selectRaw('users.*, CONCAT(users.f_name, users.f_name) as name');
}])->all();

D
D', 2016-05-30
@Denormalization

Make a method on User:

public function getNameAttribute()
{
    return $this->attributes['f_name'] . $this->attributes['f_name'];
}

And then just call:
$project->user->name;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question