I am trying to loop through selected fields within my database and then post them to the blade view page. However I cannot return the data and it returns Undefined variable: posts error message.
I have tried multiple ways to return to the view eg with->() and compact
Below is the function within my Controller which gets the posts and send them to the view.
public function getPosts()
{
$posts = Posts::all();
// return view('profile', ['posts' => $posts]);
//$profilePosts = Posts::paginate(10);
return view('page.profile' , compact('posts'));
}
Below is my foreach statement within my blade view.
@foreach ($posts as $post)
{{$post->postContent}}
@endforeach
the expected output should be a list of posts and the content which is stored in the database
Below is my Post model class
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
public function user()
{
//Relationship
return $this->belongsTo("App\User");
}
}
Hi all I found the problem with my code. firstly I included protected $table = 'posts';
within my Posts Model class, advised by @Jinal Somaiya. Then ensuring that I had the correct routes and included the below code in my PostsController index function
$posts = Posts::all();
return view('page.profile')->with('posts',$posts);
The above foreach statement in my question description is correct.
Thanks for everyones help!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.