1

i try to solve this problem and read many post but nothing help me, try to figure out my problem, as i am new to laravel!

this is my Index.blade.view located in view/posts

    <!DOCTYPE html>
<html>
<head>
    <title>Post</title>
</head>
<body>
<ul>
    <?php 
        foreach ($posts as $post) {
        echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
        }
    ?>
</ul>
</body>
</html>

PostController :

<?php

namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
    public function index(){
        $posts = Post::all();
        return view('posts.index',compact($posts));
    }

    public function showPost($id){
        $post = Post::find($id);
        return view('posts.post',compact($post));
    }
}

i read many post related to this but nothing help me, what i am doing wrong? this is the problem i am facing : Undefined variable: posts (View: C:\xampp\htdocs\firstApplication\resources\views\posts\index.blade.php)

2
  • Please post the exact error message. Commented Dec 9, 2018 at 21:18
  • @Strom Undefined variable: posts (View: C:\xampp\htdocs\firstApplication\resources\views\posts\index.blade.php) Commented Dec 10, 2018 at 8:31

2 Answers 2

1

Let's assume you have another variable holding data, then your index method should look like:

Access content of $post as $post->id instead of $post->$id

 public function index(){
     $posts = Post::all();
     $someData = []; // extra variable
     return view('posts.index',compact('posts','someData'));
 }

Another Change to be made is in view file: On a side note: you don't have to use traditional PHP tags and foreach, instead you could use Laravel's clean and elegant method like following:

Replace your block of code:

<?php 
   foreach ($posts as $post) {
      echo "<li><a href = 'post/$post->$id'>".$post->$title."</a></li>";
   }
?>

Updated code:

@foreach($posts as $post)
    <li><a href = "{{ url('post/'. $post->id) }}" </a></li>
@endforeach
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
0

Change view to

</head>
<body>
<ul>
    <?php 
        foreach ($posts as $post) {
        echo "<li><a href = 'post/$post->id'>".$post->title."</a></li>";
        }
    ?>
</ul>
</body>
</html>

Change $post->$id to $post->id and $post->$title to $post->title Also compact($posts) to compact('posts') and compact($post) to compact('post')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.