Try to get all post's by a user in application and show in a table with corresponding column , i tried with this way but showing exception : " Trying to get property of non-object " , how to solve it ?
public function usersPost(){
$uid = \Auth::user()->id;
$posts = DB::table('posts')->('user_id',$uid);
}
Here two table posts and users and user_id is foreign key of posts table .
Laravel allows you to relate models to each other. For instance, you can relate your Post model to your User model like this.
class User extends Eloquent {
public function posts() {
return $this->hasMany('Post');
}
}
After specifying that the User has many posts through a One-to-Many relationship, you can then simply call all of your user's posts.
$posts = User::find(user_id)->posts;
public function usersPost() {
$posts = DB::table('posts')->where('user_id', auth()->id())->get();
}
You need a where clause like this:
$posts = DB::table('posts')->where('user_id', $uid)->get();
Related
I have the following tables
USERS = username | email | name
FOLLOWERS = user_id | follower_id
When a logged-in user clicks on "follow" my code saves his id inside followers.follower_id, and the id of user who he wants to follow is saved inside followers.user_id.
To see how many followers a user has and how many users a user is following I use:
$followers = Follower::where('user_id', $user->id)->count();
$following = Follower::where('follower_id', $user->id)->count();
This works well, but I would like to show information about the followers of one user. I've tried the following:
$first_follower = $followers[0]->user->username;
But it return the user followed not the follower.
I am wondering how I can get information about the follower
User Model
protected $fillable = ['username','email','name'];
public function follow() {
return $this->hasMany('Shop\Follower');
}
Follower Model
protected $fillable = ['user_id','follower_id'];
public function user() {
return $this->belongsTo('Shop\User');
}
An example how you should implement relations, is above. It's many users to many users thru followers table. You probably dont need a follower model, cause you already have a user model. Your code will work after some analyze and enhancements, but i will highly recomend you to make something like this inuser model instead:
public function followers()
{
return $this->belongsToMany('App\User','followers','user_id','follower_id');
}
public function following_users()
{
return $this->belongsToMany('App\User','followers','follower_id','user_id');
}
Than you can access a followers $user->followers (this will return eloquent collection and you will be able to do whatever you want with this according to laravel docs collection api) and a certain one like $user->followers[0]
Hope i get your answer rigth.
If I get this right the followers are instances of the User class/model, so you don't need a Follower model. You can just define a Many To Many Relationship
In your User model you can add:
public function followers()
{
return $this->belongsToMany('Shop\User', 'followers', 'user_id ', 'follower_id');
}
public function following()
{
return $this->belongsToMany('Shop\User', 'followers', 'follower_id', 'user_id');
}
Than you can access the user followers just by $user->followers which will return a Laravel Collection and with $user->following you can access the ones that the user is following.
//Get the count of all followers for $user
$count = $user->followers()->count();
//Get the count of all followed by $user
$count = $user->following()->count();
//Get the username of the first follower
$follower = $user->followers()->first();
echo $follower->username;
//Loop trough all followers
foreach ($user->followers as $follower) {
echo $follower->username;
}
Defining this relation can help you save/delete followers just by using the attach() and detach() methods
// The $user will be followed by an user with $followerId
// A record in the `followers` table will be created with
// user_id = $user->id and follower_id = $followerId
$user->followers()->attach($followerId);
// The $user will stop be followed by an user with $followerId
$user->followers()->detach($followerId);
A side note:
There is a difference between calling the followers() method and calling the followers property. The first will return BelongsToMany relation and you can call all the Eloquent query builder method on it and the later will return a Collection
/** #var Illuminate\Support\Collection */
$user->followers;
/** #var Illuminate\Database\Eloquent\Relations\BelongsToMany */
$user->followers();
I have a has many relation between models: post and category in laravel application. I've defined these relations as:
public function category() {
return $this->belongsTo('artSite\category');
}
public function posts() {
return $this->hasMany('artSite\post');
}
Now I'm trying retrieve posts belonging to the particular category which are derived in http request:
Route::get('posts/categories/{categoryName}','postsViewController#showPostGivenCategory')
Below I show my controller function (it does work fine!):
public function showPostGivenCategory($categoryName) {
$category = category::where('category_name','=',$categoryName)-first();
$posts = category::find($category->id)->posts;
return view('pages.homePage')->with('categories',$categories)with('posts',$posts);
}
In this solution I'm creating 2 queries. Is any possible way to create 1 query to retrieve posts of particular category in has many relation?
Something like that doesn't work:
$posts = category::where('category_name','=',$categoryName)->posts;
Could someone help me with this problem? I would be very grateful, greetings.
we can get rid of the second line :
$posts = Category::find($category->id)->posts;
So You can say :
$posts = Category::where('category_name','=',$categoryName)->first()->posts;
I want to get column list with Eloquent relation in laravel.
When I use this comman
$columns = Schema::getColumnListing('news');
Result is all fields of news table but I want to get relation fields for CategoryNews table.
News model:
public function NewsCategories()
{
return $this->belongsTo('App\CategoryNews');
}
CategoryNews model:
public function News()
{
return $this->hasMany('App\News');
}
You should be able to do something like this:
$columns = Schema::getColumnListing($news->NewsCategories()->getRelated()->getTable()));
Using getRelated() method you are getting related object for relationship (in your case it's App\CategoryNews) and now using method getTable() you can get table name for this model and you can use this table name for getColumnListing() method.
I'm new to laravel and I'm using Laravel 5.2 I want to have all the comments of a particular post of a user. My tables are like :
User
-----
id
public function posts() {
$this->hasMany( 'App\Posts' )
}
Post
------
id
user_id
public function user() {
$this->belongsTo( 'App\User' )
}
public function comments() {
$this->hasMany( 'App\Comment' )
}
Comments
----------
id
post_id
public function post() {
$this->belongsTo( 'App\Post' )
}
Now what I want is to get all the post for a perticular user say the logged in user. I can get all the comments by the long way like :
$comments = [];
foreach( Auth::user()->posts as $post) {
foreach( $post->comments as $comment )
{
$comments[] = $comment->title
}
}
But I was wondering how to get the comments without making these loops using the relations only. Thanks in advance.
You can double the relationship from the existing user object:
$posts = \Auth::user()->posts()->with('comments')->get();
It should work for all levels.
In my project I have Organizations with Clients with a link table to Therapists, all multiple, and this works:
Organization::find(1)->clients()->with('therapists')->get();
so your case should work too. Let me know.
Essentially you want to eager load your data using with() and dot notation like so:
$user = User::with('posts.comments')->find(Auth::user()->id);
If you just want the comments, you can do:
$user = User::with('comments')->find(Auth::user()->id);
$comments = $user->comments();
I have three tables like this:
**Users**
id
**Posts**
id
user_id
**Favorites**
id
user_id
post_id
Currently, I made it so when I query my posts for display, it pulls all the related user data who created the post with that row which is great! But what I'm trying to do now is also add to see if the user Authorized (Logged in) has favorited the post (row) so I can display to that they already favorited it. I don't want to re-query for every post (i think its called the N+1 problem?). I'm using Laravel4
Post model
class Post extends Eloquent{
public function user(){
return $this->belongsTo('User');
}
User model
public function posts(){
return $this->hasMany('Post');
}
PostsController
public function index()
{
$posts = Post::with('user')->paginate(25);
return View::make('index', compact('posts'));
}
Step 1. Add favorites relationship in Post model.
public function favorites() {
return $this->hasMany('Favorite');
}
When querying the Model.
$auth_user_id = Auth::user()->id;
$posts = Post::with(array('user', 'favorites' => function($query) use ($auth_user_id){
$query->where('user_id', '=', $auth_user_id);
}))->get();
For more information refer to the eager load constraints,
http://laravel.com/docs/eloquent#eager-loading
Adding a many-to-many relationship using the favorites table as pivot would be one approach.
Add favorites relationship in User model:
public function favorites() {
return $this->belongsToMany('Post', 'favorites');
}
You should then be able to get all favorites by simply accessing
Auth::user()->favorites
To find whether the current post is a favorite, use
$isFavorite = Auth::user()->favorites->has($post->id);