'Retrieve All Posts and the user data data in Laravel
The Parent Model - User
public function posts() {
return $this->hasMany(Post::class);
}
The Child Model- Post
public function user_posts() {
return $this->belongsTo(User::class,"id");
}
Now in the Route, I was trying to print- Every post and the name of the admin -
Route::get("/admin/posts",function() {
$posts = Post::all();
foreach($posts as $post) {
$userId = $post->id;
$userName = Post::findOrFail($userId)->user_posts->name;
echo "<pre>
Title - $post->title
Content - $post->content
Author - <mark>$userName</mark>
</pre>";
}
});
By running this code it only prints only the first post of the admins and shows an error Trying to get property 'name' of non-object
Pulling out by single post id it prints the user data it works fine
Route::get("/admin_data_by/postsId",function() {
$postId = 1;
$userName = Post::findOrFail($postId)->user_posts->name;
echo "<pre>
Author - <mark>$userName</mark>
</pre>";
});
Migrations- User
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Migration- Post
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->integer("user_id")->unsigned()->nullable()->index();
$table->string("title");
$table->text("content");
$table->timestamps();
});
}
Solution 1:[1]
just change your route method to the following and and everything will work for you
$postId = 1;
$userName = Post::firstOrFail('id', $postId)->user_posts->name;
echo "<pre>
Author - <mark>$userName</mark>
</pre>";
Solution 2:[2]
you first get object and show parameters in object
please get data with below code
$user = Post::findOrFail($userId);
$post = $user->user_posts;
echo "<pre>
Title - $post->title
Content - $post->content
Author - <mark>$post->name</mark>
</pre>";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Junaid Masood |
| Solution 2 | Reza ghz |
