Support the ongoing development of Laravel.io →
Database Eloquent Views

Hi there, I'm very new to Laravel and I'm creating a dummy blog application to help me understand the framework and I just wanted some advice on how to develop the following.

I have a table called posts which contains the following columns:

id title text author category_id created_at updated_at

My plan is to have a lookup table called categories and this contains two columns:

id type

In the view I will have populated the category drop down list with the data from the categories table, so when submitting the post, the id from the category table is submitted to the posts table within the category_id column. I want the app to look at the category_id from posts and cross reference this with id in the categories table and therefore return the value from type into the view.

So for example, we select a category of PHP, this has an id of 5 in the category table. App looks at post table, picks up the category_id of 5 and returns the word PHP against this post in the view.

Any ideas?

Thanks!

Last updated 2 years ago.
0

Define category relation for Post models (supposing you have 'Category' model)

public function category(){
    return $this->belongsTo('Category');
}

Now from a post you can access to category:

$post = Post::find(1);
echo $post->category->type;

Take a look at this link: http://laravel.com/docs/eloquent#relationships

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

jbradley22 jbradley22 Joined 23 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.