T. Cem Yılmaz
T. Cem Yılmaz

Reputation: 510

Laravel JSON Response with Eloquent

I got three tables called threads,posts,users

threads got

id
title
etc.

posts got

id
thread_id
user_id
post
post_date
etc.

users got

id
username 
password
email
etc.

when users wants to view a thread i simply call a jquery ajax request using post data to send thread id and return this code :

Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get());

this code does his job perfectly and return posts by same thread_id. (post model also eager loads the user by looking user_id).

however this code grabs every attribute of posts and users i mean everything to json, post_date, post_updatereason, user_password, user_email all columns in tables.

I just want to grab post, username and post_date with json

Upvotes: 0

Views: 3348

Answers (2)

Bartek
Bartek

Reputation: 1059

You can add public static $hidden = array('list', 'of', 'fields'); to your model which extends Eloquent. Then none of the fields which you enumarate in the array will be returned. For more information refer to the documentation.

For example

class User extends Eloquent {
  public static $hidden = array('password', 'email');
}

will return the user model without the password and email.

Upvotes: 4

Blessing
Blessing

Reputation: 4888

If you are using laravel 3, and this is probably the same for version 4, you should be able to specific the columns you want using the get method.

Response::eloquent(Thread::find(Input::get('threadid'))->posts()->get(['username','post_date']));

Upvotes: 1

Related Questions