我一直在尝试解决我的 Laravel 应用程序中的错误,但到目前为止我一直没有成功。我已经尝试了所有我能想到的方法,包括使用 compact 函数和 with 方法将 $names 变量传递给视图,但我仍然收到错误消息“Undefined variable $names”。
我不确定此时还能做什么,如果有人能提供任何帮助或建议,我将不胜感激。谢谢。
CONTROLLER:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Name;
class NameController extends Controller
{
public function index()
{
$names = Name::all();
return view('names.index', compact('names'));
}
public function create()
{
return view('names.create');
}
public function store(Request $request)
{
$name = new Name;
$name->fill($request->all());
$name->save();
return redirect()->route('names.index');
}
public function show($id)
{
$name = Name::findOrFail($id);
return view('names.show', compact('name'));
}
public function edit($id)
{
$name = Name::findOrFail($id);
return view('names.edit', compact('name'));
}
public function update(Request $request, $id)
{
$name = Name::findOrFail($id);
$name->fill($request->all());
$name->save();
return redirect()->route('names.index');
}
public function destroy($id)
{
$name = Name::findOrFail($id);
$name->delete();
return redirect()->route('names.index');
}
}
<?php
<?php
MODEL:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Name extends Model
{
use HasFactory;
protected $fillable = ['first_name', 'last_name'];
}
INDEX:
<h1>Names</h1>
<a href="{{ route('names.create') }}">Add Name</a>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Second Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach ($names as $name)
<tr>
<td>{{ $name->id }}</td>
<td>{{ $name->first_name }}</td>
<td>{{ $name->last_name }}</td>
<td>
<a href="{{ route('names.show', $name->id) }}">View</a>
<a href="{{ route('names.edit', $name->id) }}">Edit</a>
<a href="{{ route('names.delete', $name->id) }}">Delete</a>
</td>
</tr>
@endforeach
</tbody>
</table>
我是初学者:)