0
votes

I am new to laravel, and getting this error though tried every possible sites and google searches. I even tried previous queries solution from stack overflow, but was unable to solve.

this is my PostController.php:

`public function getData()
{
    $post['post']=DB::table('students')->get();
    if(count($post)>0){
        return view('index',['Post'=>'$post'] );
    }
    else{
        return view('index');
    }
}`
this is my controller

This is my index.blade.php:

`@foreach($post as $value)
 <tr>
 <td>{{$value->id}}</td>
 <td>{{$value->name}}</td>
 <td>{{$value->address}}</td>
 <td>{{$value->number}}</td>
 <td><a href="" ><button>Edit</button></a>&nbsp; <a href="" > 
 <button>Delete</button></a></td>
 </tr>`

This is my blade:

Route::get('/index','PostController@getData');

this is my route

please help in this queries, i am having a lots of problem

2

2 Answers

2
votes

There are a number of problems with your code. I would recommend you go through laravel documentation and first 2 PSRs

As error clearly states that there is not a variable $post in the view. In else you are not sending the $post variable and in if you are sending the $post variable with a capital P but you are accessing it using lower case p in your view. So the variable is not available in any case in the view that's why it is showing that error.

PHP variables are case sensitive and do not use the quotes around php variable (the one with $ sign) in the parameters that you are passing to the view.

return view('index',['Post'=>'$post'] );

Above statement should be written as

 return view('index',['post'=>$post] );

also update your controller method and I don't know why are you using associative array ($post['post']).

public function getData()
{
    $post = DB::table('students')->get();
    return view('index',['post'=>'$post'] );
}
0
votes

I identified this problem. You send the posts variable in the index function.

public function index(){
    $posts = Post::all();
    return view('posts.index',compact('posts'));
}

But most likely you get this error when you want to create a new post, so here the store function is executed and the index function is not executed in the controller, because the store function is responsible for storing form information. Then you edit this function as follows.

public function store(Request $request) {
    $post = new Post();
    $post->title = $request->input("title");
    $post->description = $request->input("description");
    $post->save();


    $posts = Post::all(); //Send posts in compact
    return view("posts.index", compact($posts));
}

Excuse me for the typing problem, I am a Persian speaker ❤