Reputation: 27
i have an error.. it says:
Undefined variable: posts (View: C:\xampp\htdocs\dinsospermasdes\bansus\resources\views\admin\posts\index.blade.php)
it works in home.blade.php like this:
@foreach ($posts as $post)
<div class="card mb-4">
<img class="card-img-top" src="{{filter_var($post->post_image, FILTER_VALIDATE_URL) ? $post->post_image : '/storage/' . $post->post_image}}" alt="Card image cap">
<div class="card-body">
<h2 class="card-title">{{$post->title}}</h2>
<p class="card-text">{{Str::limit($post->body, '50', '....')}}</p>
<a href="{{route('post', $post->id)}}" class="btn btn-primary">Read More →</a>
</div>
<div class="card-footer text-muted">
Posted on {{$post->created_at->diffForHumans()}} by
<a href="#">{{$post->name}}</a>
</div>
</div>
@endforeach
but didn't work in admin/posts/index.blade.php like this:
@foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>
<img height="40px" src="{{filter_var($post->post_image, FILTER_VALIDATE_URL) ? $post->post_image : '/storage/' . $post->post_image}}">
</td>
<td>{{$post->created_at->diffForHumans()}}</td>
<td>{{$post->updated_at->diffForHumans()}}</td>
</tr>
@endforeach
this is PostController.php:
class PostController extends Controller
{
//
public function index(){
$post = Post::all();
return view('admin.posts.index');
}
public function show(Post $post){
return view ('blog-post', ['post'=>$post]);
}
public function create(){
return view ('admin.posts.create');
}
public function store(){
$inputs = request()->validate([
'title'=>'required|min:8|max:255',
'post_image'=>'file', //mime: jpeg, png
'body'=>'required'
]);
if(request('post_image')){
$inputs['post_image'] = request('post_image')->store('images');
}
auth()->user()->posts()->create($inputs);
return back();
}
}
this is routes from web.php
Auth::routes();
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/post/{post}', [App\Http\Controllers\PostController::class, 'show'])->name('post');
Route::middleware('auth')->group(function(){
Route::get('/admin', [App\Http\Controllers\AdminController::class, 'index'])->name('admin.index');
Route::get('/admin/posts', [App\Http\Controllers\PostController::class, 'index'])->name('post.index');
Route::get('/admin/posts/create', [App\Http\Controllers\PostController::class, 'create'])->name('post.create');
Route::post('/admin/posts', [App\Http\Controllers\PostController::class, 'store'])->name('post.store');
});
Upvotes: 1
Views: 65
Reputation: 15306
In index method you need to pass posts
public function index(){
$posts = Post::all();
return view('admin.posts.index',compact('posts'));
}
you're not passing posts variable
in blade file. Hence, it is giving you undefined error
.
Upvotes: 1