我正在尝试将对象发送到show
方法,但没有属性。
index.blade.php
<a href="{{ route('admin.specialities.show', [$speciality])}} "> {{$speciality->display_name}}</a>
web.php
Route::resource('admin/specialities', 'SpecialtyController',
['names'=> ['index' => 'admin.specialities',
'show' => 'admin.specialities.show',]]);
SpecialtyController.php
namespace App\Http\Controllers;
use App\Models\Backend\Specialty;
use Illuminate\Http\Request;
class SpecialtyController extends Controller
{
public function index() {
return view('specialities.specialities')
->with(['specialities' => Specialty::all()]);
}
public function show(Specialty $specialty) {
dd($specialty); //<- always null atributes
return view('specialities.show', compact('specialty'));
}
}
Specialty.php
namespace App\Models\Backend;
use Illuminate\Database\Eloquent\Model;
class Specialty extends Model
{
/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}
}
任何想法可能出什么问题或在哪里检查?
答案 0 :(得分:0)
您应在路线上通过id
:
<a href="{{ route('admin.specialities.show', $speciality->id)}} "> {{$speciality->display_name}}</a>
在您的控制器中,您可以找到特定的模型:
public function show(id)
{
$speciality = Specialty::FindOrFail($id);
return view('specialities.show', compact('speciality'));
}
将索引方法更改为:
public index()
{
$specialities = Specialty::all();
return view('specialities.specialities', compact('specialities'));
}
注意
声明变量时要小心,您有一个名为 Specialty 的模型,但是表示该模型的变量为$speciality