T
T
Tarasovych2017-04-22 00:24:15
Laravel
Tarasovych, 2017-04-22 00:24:15

How to correctly pass a model property?

There is a method that, judging by the result, transfers existing records from the database to the view:

public function index(Request $request)
    {
        $text = Text::orderBy('id','DESC')->paginate(5);
        return view('text.index',compact('texts'))
            ->with('i', ($request->input('page', 1) - 1) * 5);
    }

How to get a property of a model that is associated with a model Text?
That is, for example, there is a model User, each Texthas one User'a, and you need to display a Textproperty for each instance User'a- its name.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav, 2017-04-22
@Tarasovych

It's called relationships !
In the User model, write:

public function text()
    {
        return $this->hasOne('App\Text', 'user_id', 'id');
    }

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

Call
<?=$text->user->name ?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question