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
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.
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']));
Related
I have user role relation (many to many) defined as follows in Role model:
public function users()
{
return $this->belongsToMany('App\User');
}
Now I want to show all users in certain role. I execute the following:
$list = Role::find(1)->users()->select('name')->orderBy('name')->paginate(10);
Here $list contain all users that belong to role with id 1 and that is correct. But the problem is: when adding breakpoint on $list it shows that: all user model's attributes are retrieved just like select('name') has no effect.
This is a big problem especially when i want to return the $list as json. User password is retrieved even though it's in the $hidden array of User Model.
My question is:
why paginate() on querybuilder does not respect select() nor attributes in model's $hidden array?
Note: I know that there is other solutions to achieve what I want. I just want an answer to my question to figure out what is going on?
select('name') has no effect because paginate() method takes columns as second parameter
$list = Role::find(1)->users()->orderBy('name')->paginate(10, ['name']);
You can read more about parameters and methods here
https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_paginate
Since users have the role_id then why don't you fetch the users as:
User::where('role_id', 1)->orderBy('name')->paginate(10);
You are basically getting a role and then fetching a list against that role.
I have posts, users and favorites table.
For example, I make some post favorited for a user with an id of 3 like this :
User::find(3)->favorites()->attach($post->id);
and if users send request twice it will insert this favorite with this post_id, user_id twice.
I want to check if a post is not liked by this user, then save record in the database.
or if a post is favorited then unfavorite it.
how can I do this with eloquent relationship ??
I have User, Post models.
You could use toggle():
User::find(3)->favorites()->toggle($post->id);
This would like it if it not liked, and unlike it if it is.
If you just want the function not to duplicate likes in the table, just use syncWithoutDetaching:
User::find(3)->favorites()->syncWithoutDetaching([$post->id]);
Putting this on your User model:
class User extends Model {
public function like($postId){
$this->favorites()->syncWithoutDetaching([$post->id]);
}
public function unlike($postId){
$this->favorites()->detach([$post->id]);
}
}
Let's say I have User model with the following attributes:
uid
username
password
dob
usergroup
avatar
When providing JSON I should hide the password, so I will write:
$protected $hidden = ['password'];
When a request is being made for user data, I would like the model to respond with only: uid, avatar, dob.
When a request is being made for security data, I would like the model to respond with only: uid, username, usergroup.
How can I set predefined groups of $visible and $hidden attributes for different request inside model configuration, without using controllers which will make my code messy.
As #maiorano84 mentioned in the comments you wouldn't add multiple $hidden/$visible properties for this. These properties are more for general purpose so you don't have to worry about removing certain attributes each time you just want to return an instance in a request.
If you're only wanting to return specific fields in certain requests then you would be more explicit about it.
In one of your examples above you mentioned only returning uid, username and usergroup which you could do with the something like:
return collect($user)->only('uid', 'username', 'usergroup');
Hope this helps!
Trying to figure what table I need to make this relationship to work...
I'd like the user to mark a post as favorite and save it so when he log back in, he can view all his favorite posts.
So I have User and Post models and their relationships of course.
User hasMany Post, Post belongTo User
Do I need to add Favorite model and add fav_id to both User and Post models ?
Or maybe adding pivot table?
If a favorite is defined as a simple relationship between users and posts, you don't need a model for it. However, you do want a pivot table, call it something like favorites. It would contain id, post_id, user_id, created_at, updated_at.
Then in your user model:
public function favoritePosts()
{
return $this->belongsToMany('Post', 'favorites');
}
And in the post model:
public function favoritedBy()
{
return $this->belongsToMany('User', 'favorites');
}
So now, for any given user, you can do $user->favoritePosts to get an array of posts that user has "favorited".
And from a post object, you can do $post->favoritedBy, to get an array of users that have favorited that post.
I haven't tested this but that seems like that would work off the top of my head.
how can I pull all the posts of a certain user? should i foreach all the posts of a certain user? Like if user1 posted something and I want to pull out whatever he posted and only shows when he's logged in.
In Laravel, if you are using Eloquent relationships things would look something like this.
First, define your relationships within your models. If you're following the example below, I'm going to assume the following.
Your users table in database is named users. Your posts table in
database is named posts, and has an integer column named user_id
corresponding to the id of the user the post belongs to. If your
table and column names are different, make sure you read the Laravel
docs to learn how to set custom table names and column names for
Eloquent models.
app/models/User.php
<?php
class User extends Eloquent {
// All the default User.php stuff....
public function posts()
{
return $this->hasMany('Post');
}
}
app/models/Post.php
class Post extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
After we've defined those relationships, you can get a particular user using something like this.
$user = User::find(1); // This will get the user with an ID of one.
Then, you retrieve that user's posts, we can use the Eloquent relationship we defined earlier.
$posts = $user->posts()->all();
If the user is already logged in, you can user the Auth class to do this for the logged in user.
$posts = Auth::user()->posts()->all();
You'll now realize that ->posts() actually returns a Collection, and you can use all of the Query and Eloquent methods on that collection as normal.