Reputation: 7
I follow the guide ( https://www.phpflow.com/php/laravel-5-6-crud-operation-using-resource-controller/ ) and at point "How To Create Listing in Laravel 5.6" I get the error::
ErrorException (E_ERROR) Undefined variable: employees (View: C:\xampp\htdocs\crud\resources\views\pages\index.blade.php)
Previous exceptions * Undefined variable: employees (0)
And in code window the error is:
<?php
$__currentLoopData = $employees;
$__env->addLoop($__currentLoopData);
foreach($__currentLoopData as $key => $emp):
$__env->incrementLoopIndices();
$loop = $__env->getLastLoop(); ?>
Is it a compatibility issue between 5.6 and 5.7 or what? (please note that I am a noob in Laravel)
Upvotes: 0
Views: 21528
Reputation: 1856
The guide is pretty slim, what you need to do in order to get you index working:
namespace App\Http\Controllers;
use App\Employee;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
return view('pages.index', ['employees' => Employee::all()]);
}
// ... The rest of the controller method below
}
If your resource definition is:
Route::resource('employee', 'EmployeeController');
The Path (URL) to access this will be: /employee
Upvotes: 2
Reputation: 7
The error remains, part of my code so far, EmployeeController.php:
public function index()
{
$employees = Employee::all();
return view('employee.index', ['employees' => $employees]);
}
Employee.php
class Employee extends Model
{
// Table name
protected $table = 'crud';
// Primary key
public $primaryKey = 'id';
}
index.blade.php
<tbody>
@foreach($employees as $key => $emp)
<tr>
<td>{{ $emp->id }}</td>
</tr>
@endforeach
</tbody>
Upvotes: 0
Reputation: 1835
According to your link I do not see the full code of the controller, but your index
method should look like this
public function index()
{
$employees = Employee::all();
// Pass data to view
return view('employee.index', ['employees' => $employees]);
}
Upvotes: 1