#@foreach error message
28 messages · Page 1 of 1 (latest)
Read the error message?
It’s telling you what the problem is.
You also should not be wrapping variables in single quotes here:
@foreach (‘$posts’ as ‘$post’)
Remove the quotes:
@foreach ($posts as $post)
Yes sorry was writing on my phone and copied it wrong. I’m a beginner and not sure what the problem is
When I dd $posts I get the correct table. When I dd $post I get a laravel directory
//resources/views/themes/tailwind/posts/index.blade.php
Idk why $post isn’t giving me a single post from the table of $posts and is instead pointing to a directory
Show the controller/route where you pass $posts to your view.
i have a post model
"`class Post extends Model
{
protected $table = 'Posts';
} `"
and i have a posts controller
"` public function index()
{
$posts = DB::table('posts')->find(1);
return view('theme::posts.index', [
'posts' => $posts
]);
} `"
If you want to pass all the posts to the view and loop through them you can do this in the index method of your controller
$posts = Post::all();
And pass it to the view as you have done.
Don’t forget to import/use the Post model in the controller though 😁
@muted lodge
when i try this it says $post is an undefined variable
am i not importing the DB correctly by using the model? im confused as to how this is working now since....it's not working
it does work when i do it specifically as i did here "$posts = DB::table('posts')->find(1);" but only for $posts and not $post
the $post in the foreach is still returning a directory
You still need to loop through the posts in the view.
@foreach ($posts as $post)
yes i have
Can you show me your controller please, including the top where you import the classes.
yes i will post again later sorry gtg
best of luck
Well this is the problem. You’re using find. That’s going to return either a single model, or null if the model with that primary key value does not exist. Basically your code is very error-prone, and you’re trying to iterate over a single model instance instead of a collection of models, which isn’t going to work.
So I don‘t understand why you’re trying to find a post with an ID of 1, but then trying to loop over it? What are you expecting here?
well, when i used get() it didn't work at all and i'm a super noob, i can't stress that enough, so i was exploring to see what worked
i agree, what i actually want is the entire table, not one single thing