one to may relationship, Display all post along with there users - laravel

//Post table
user()
`belongsTo(User::class);`
//user table
posts()
hasMany(post::class);
//I want to get all the post available in the DB, Display along with the users associated with the post.

Use foreign key and primary key in relationships to get the results.
In Post
public function user()
{
return $this->belongsTo('App\User','users_id','users_id') //first parameter-foreign key,second parameter-local key
}
In User
public function posts()
{
return $this->hasMany('App\Post','users_id','users_id')
}
Now get all the posts using
$posts = Post::get();
return view('your-view')->with('posts',$posts);
You can retrieve user information in view using
#foreach($posts as $post)
$user = $post->user->name;
#endforeach
Hope it helps..

Guessing your relations look like this:
User:
public function posts()
{
return $this->hasMany('App\Post');
}
Post:
public function user()
{
return $this->belongsTo('App\User')
}
You could get all the posts in your controller, like this:
$posts = Post::get();
return view('your view', $posts);
And in your blade, to display posts and their users, do it like this:
#foreach($posts as $post)
$post->user->name
#endforeach

$posts = Post::with('user')->get();

Related

Why Eloquent HasMany return an empty collection?

Hi why i get an empty collection when i use $user->posts as property. However i do a get collection when i use $user->posts() as function.
public function user(){
return $this->belongsTo(User::class);
}
public function posts(){
return $this->hasMany(Post::class);
}
public function index(User $user){
dd($user->posts);
return view('home', compact('user'));
}
#foreach($user->posts as $post)
<p>$post->title</p>
<p>$post->body</p>
#endforeach
result
Collection {#1102 ▼
#items: []
}
The first method (user) should be in your post model.
The second method (posts) should be in your user model.
Check your database and see if the posts table has a column named user_id.
Check your database and see if the user_id column has a valid value (according to the users table.
Also make sure your route has {user} in it. Something like this:
Route::get('home/{user}', 'Cotroller#method')
User model:
public function posts(){
return $this->belongsTo(User::class);
}
Post model:
public function user(){
return $this->hasMany(Post::class);
}
And make sure you have user_id column on your post table

Trying to retrieve posts from table by category slug

Hello i am trying to loop posts that are associated to each category by the slug. It works when i use the ids but when i change my controller function to search by slug it retrieves the slug but does not load the foreach loop.
I have tried so many methods and i don't know where i am going wrong please help.
Category Model :
protected $table = 'post_categories';
public function posts()
{
return $this->hasMany('App\Post', 'id', 'name', 'catslug');
}
Post Model
public function user()
{
return $this->belongsTo('App\User');
}
public function postCategories()
{
return $this->belongsTo('App\PostCategory');
}
Controller
public function getPostCategory($catslug) {
$postCategories = PostCategory::with('posts')
->orderBy('name', 'asc')
->where('catslug', '=', $catslug)
->first();
return view ('articles.category.categoriesposts')->with('postCategories', $postCategories);
}
Route
Route::get('articles/category/{catslug}', [
'uses' => 'ArticlesController#getPostCategory' ,
'as' => 'PostCategory'
] );
View
#foreach($postCategories->posts as $post)
<h4>{{ substr($post->title, 0, 50) }}</h4>
<p>{{ substr($post->body, 0, 90) }}</p>
#endforeach
When i use id there is no problem i cant see what i am doing wrong any feedback will be truly appreciated
Thanks
Ash
Save category id in posts table insted of category name or slug.
Change in post category model:
public function posts()
{
return $this->hasMany('App\Post', 'category_id');
}
Your controller method:
public function getPostCategory($catslug)
{
$postCategories = PostCategory::with('posts')->where('catslug', $catslug)->first();
return view('articles.category.categoriesposts')->with('postCategories', $postCategories);
}
If you want to order posts by name then add orderBy() in relationship :
public function posts()
{
return $this->hasMany('App\Post', 'category_id')->orderBy('name', 'asc');
}

how to fetch commented name on posts in laravel 5.4

i followed the convention to avail the required data with compact method to view
Schema User Table
id,name,email,password
Schema post Table
id,user_id,title,body,photo
Schema comment Table
id,post_id,user_id,comments,photo
in user model
public function post()
{
return $this->hasMany(post::class);
}
public function comments()
{
return $this->hasMany(comment::class);
}
in post model
Public function User()
{
return $this->belongsTo('App\User');
}
public function comments()
{
return $this->hasMany(comment::class);
}
in comment model
public function posts()
{
return $this->belongsTo('App\post');
}
in controller
$list = User::with('post','comments')->paginate(1);
return view('dynamic',compact('list'));
in view
#foreach($lists->comments as $comments)
{{$comments->name}}
#endforeach
post showing successfully according to users
and comments showing successfully according to posts
but commented name not showing up // please help
how to make relationship for fetch comments with commented user name
please help thanks in advance
you have to change your code as below
#foreach($lists->comments as $comments)
{{$comments->posts->user->name}}
#endforeach
or
you need to add relationship to your comment model as below
Public function User()
{
return $this->belongsTo('App\User');
}
after that you need to change your code as below
#foreach($lists->comments as $comments)
{{$comments->user->name}}
#endforeach
change code as below in your view:
#foreach($lists->comments as $comments)
{{$comments->User->name}}
#endforeach

Get username from ID

I have a blade template in a Laravel 5.5 app that is returning a user ID integer
I am looking for a way to get the users name from that value within the blade template
The value is just saved in the table and there is no relationship setup, is there a way to get the username without having to set up a relationship?
** UPDATE **
My products controller looks like this...
public function index()
{
$users = User::all();
$products= Product::all();
return view('products.index',compact('products', 'users'));
}
So now I have the users available inside the blade template but now I need to get the user from the id that is contained in produts
In your controller that's passing the user data to the view, you can either pass the entire $user object and print it in your view like {{ $user->name }} or set yourself a variable that holds just the username and pass that in for however you're using it.
I would do the first one though, something like:
public function index()
{
$user = User::where('id',$id)->firstOrFail();
return view('dashboard.index', compact('user'));
}
Or if you're getting all users from the database, an example would be:
public function index()
{
$users = User::all();
return view('dashboard.index', compact('users'));
}
Then in your view you can do
#foreach($users as $user)
{{ $user->name }}
#endforeach
Edit
Since seeing your updated question, you would benefit from making a relationship between your users and your products. So, you would say that a user has many products and that a product belongs to a user.
class User extends Model
{
/**
* Get all of the products for the user.
*/
public function products()
{
return $this->hasMany('App\Product');
}
}
And then
class Product extends Model
{
/**
* Get the user that is assigned to the product
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
Once you have set this up, you can loop through your products and get the username like this:
#foreach($products as $product)
{{ $product->user->name }}
#endforeach
Create helper file: follow this rule to make it : https://laravel-news.com/creating-helpers
and make one function like this:
function getUsername($uerId) {
return \DB::table('users')->where('user_id', $userId)->first()->name;
}
and call this function from your view like this :
{{getUsername($id))}} //it will print user name;
{{\App\User::findOrFail($id)->name}}
Auth::user()->name if user is online. if not you must have controller function like:
$users = User::all();
and in blade
#foerach($users as $user)
{{$user->name}}
#endforeach

Access user's properties (with pivot table) laravel 5.1

I have a users table. The user has possibility to upload a post. The post is saved well to the database. The users can follow each other - so on a pivot table each follower_id has followees_id.
I need to get the posts of the current user followee's . I am kinda messed with getting it from a pivot table.
Here's my code so far:
controller:
protected function get_followee_posts($followee_posts) ////$followee_posts passed from the route.
{
$user = $this->user;
$user->followee()->attach($followee_posts);
$followee_posts = User::find($followee_posts);
}
view:
<div class="following_posts">
<p> Posts from people you're following: <p>
#foreach ($user->follower_id->followee_id->posts as $post)
<form action="/html/tags/html_form_tag_action.cfm" method="post">
<textarea name="comments" id="comments" style="width:96%;height:90px;background-color:white;color:black;border:none;padding:2%;font:22px/30px sans-serif;">
{!! $posts->full_post !!} </textarea>
</form>
#endforeach
route:
Route::get('hub/{followee_posts}','HubController#get_followee_posts')->name('followee_posts');
I am getting an error with the current code saying:
ErrorException in 7340f90cc5faf1a298fcc646b7248b22 line 105:
Trying to get property of non-object
Any help would be lovely. Thank you.
Your not too specific about your schema, but this is how I would go about it.
User Model
class User extends Model
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post');
}
public function followers()
{
return $this->hasMany('Follower');
}
}
Follower Model
class Follower extends Model
{
protected $table = 'followers';
public function user()
{
return $this->belongs_to('User');
}
public function posts()
{
return $this->hasMany('Post', 'user_id', 'follower_id');
}
}
Post Model
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongs_to('User');
}
}
The followers table would look something like this:
user_id
follower_id
You could then use eloquent method chains to get the posts of a users followers:
// Get Users object with followers and followers posts
// We use with() to eager load relationships
$user = User::with('followers.posts')->find(2);
// Return associative array of post objects
$postsArray = $user->followers->lists('posts');
// Combine posts into a single collection
$posts = (new \Illuminate\Support\Collection($postsArray))->collapse()->toArray();
print_r($posts);

Resources