Reputation: 151
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)
Upvotes: 1
Views: 992
Reputation: 3450
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
Upvotes: 1
Reputation: 8618
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')
Upvotes: 0