0

working with laravel 5.7 and need display student table data in the home page, home.blade.php

<table class="table">
    <thered>
     <tr>
         <td>Id</td>
         <td>Name</td>
         <td>Address</td>
         <td>Telephone</td>
         <td>Actions</td>
     </tr>
    </thead>

    <tbody>
      @foreach ($students as $student)
      <tr>
        <td>{{$student->id}}</td>
        <td>{{$student->name}}</td>
        <td>{{$student->address}}</td>
        <td>{{$student->telephone}}</td>
        <td><a class="button is-outlined" href="">Edit</a></td>
        <td><a class="button is-outlined" href="">Delete</a></td>
      </tr>
      @endforeach
    </tbody>
</table>

StudentController.php

public function index()
{
    $students = Student::all();

    return view('home');
}

web.php

Route::get('StudentController@index');

but got this error msg like this,

Undefined variable: students (View: D:\exam\curd\resources\views\home.blade.php)

How can I fix this problem?

Rwd
  • 34,180
  • 6
  • 64
  • 78
banda
  • 402
  • 1
  • 7
  • 27

2 Answers2

1

You need to pass the students to the view, so in your controller add this instead:

return view('home', compact('students'));

And your route to this:

Route::get('/home', 'StudentController@index'); // if this is your root route
nakov
  • 13,938
  • 12
  • 60
  • 110
  • did it but same error here – banda May 04 '19 at 08:54
  • @banda that's not possible unless you are not loading the page through that controller method. Check my edit for the route. – nakov May 04 '19 at 08:57
  • used above route also but not success here, same error here – banda May 04 '19 at 09:02
  • Can you try dumping out something in the controller, to make sure that you at least enter there? In your index function try `dd('test');` if this is printed in your browser. – nakov May 04 '19 at 09:03
  • try with this `public function index() { dd('test'); $students = Student::all(); return view('home')->withStudents($students); }` but same error here – banda May 04 '19 at 09:05
  • Yes, so the error is because you don't even load the page through that controller method. Can you give me the url that you are trying to access? – nakov May 04 '19 at 09:06
  • http://localhost:8000/home – banda May 04 '19 at 09:08
  • so try the route I've modified above. And make sure you don't have another `/home` route in your routes file. – nakov May 04 '19 at 09:08
  • 1
    fine @nakov now it is working fine – banda May 04 '19 at 09:11
0

You need to pass the $students variable in view. You can do that by using compact() function or there are many other way.

public function index()
{
    $students = Student::all();
    return view('home', compact('students'));
}
Md.Sukel Ali
  • 2,987
  • 5
  • 22
  • 34