Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shows undefined variable when changing the variable name

In my controller page I am trying to return all the data from mode to view. I have kept all the data in a variable and passed on to the view page. When I keep the variable name as $post I am getting error:

Undefined variable: post (View: C:\xampp\htdocs\laravel\lsapp\resources\views\posts\index.blade.php)

Controller Page

// PostController.php
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;

class PostController extends Controller
{
    public function index()
    {
        $post = Post::all();   
        return view('posts.index')-> with('posts', $post);
    }
    //remaining code blocks

view page code

@extends('layouts.app')

@section('content')
<h1>this is index page.</h1>
@if(count($post) > 1)
    <h2>testing</h2>

@else
    <p>No Data</p>
@endif

@endsection

When I change the variable name as $posts it works fine. Why does I have to keep same variable name as posts first parameter?

return view('posts.index')-> with('posts', $posts);  // it works fine
like image 964
user4221591 Avatar asked May 22 '26 20:05

user4221591


1 Answers

Becouse in with method you pass with('variableName', $variable') and in view you can use $variableName variable

Change your controller

 return view('posts.index')-> with('posts', $posts);

And view

@if(count($posts) > 1)

Or you can change your controller

 return view('posts.index')-> with('post', $posts);

And view

@if(count($post) > 1)
like image 154
Davit Zeynalyan Avatar answered May 24 '26 19:05

Davit Zeynalyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!