Zaeem Syed
Zaeem Syed

Reputation: 111

Retrieve data from database using key in the view file

I am trying to retrieve data from my database and show it in my view but there I get an error.

Here is my controller

public function index()
{            
  $Page=Superior::all();

  return view('Myview.Firstpage')->with('Task',$Page);
}

And this is where I assign in the view

<body>
<p>this is our first page </p>

{{ $Task }}


</body>
</html>

but this task is creating error and it says that the Task is an undefined variable my whole page looks like this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>This is our first page </title>
</head>
<body>
<p>this is our first page </p>

{{ $Task }}


</body>
</html>

Superior is the name of my model from which I want to retrieve my data.

My routes files in web.php is

<?php




Route::get('First',function(){
    return view('Myview.Firstpage');
});

i am learning laravel

Upvotes: 1

Views: 106

Answers (2)

Milena Grygier
Milena Grygier

Reputation: 396

Hi please try to pass you variable to view like this:

$Tasks = Superior::all();
return view('Myview.Firstpage', compact('Tasks'));

And then use a loop in your view like suggested in above comments.

   @foreach($Tasks as $task)

     {{ $task->title }}

 @endforeach

Upvotes: 1

fakorede
fakorede

Reputation: 783

In the index method of your controller

public function index()
{

     return view('Myview.Firstpage')->with('tasks',Superior::all());

}

Keep in mind that the all() method returns a collection which you want to loop through in your view.

In your view, you should have:

    @foreach($tasks as $task)

         {{ $task->title }}

    @endforeach

You need to also update your route to make use of the controller:

Route::get('/', 'TaskController@index');

You could visit https://laravel.com/docs/5.8/collections#method-all to learn more about collections.

Upvotes: 1

Related Questions