如何解决一切正常,在URL中获取ID,但未使用资源控制器针对ID显示数据
我尝试使用show方法(资源控制器)显示特定用户的数据 但是出现404错误。索引,创建和存储功能都很好。 在URL中获取ID,但在调用show函数时显示404错误 编辑,更新和销毁时出现相同的错误。我尝试在没有资源控制器的情况下正常运行。
这是我的代码,
<table class="table table-striped table-inverse table-responsive">
<thead class="thead-inverse">
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
@foreach ($data as $item)
<tr>
<td scope="row">
{{$item->id}}</td>
<td>
{{$item->name}}</td>
<td>
{{$item->email}}</td>
<td><a href="{{ route('show',$item->id) }}">edit</a></td>
</tr>
@endforeach
</tbody>
</table>
资源控制器的代码,索引,创建和存储功能没有问题 当我将id作为参数传递时,只会得到404错误
<?php
namespace App\Http\Controllers;
use App\crud;
use Illuminate\Http\Request;
class CrudController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data=crud::all();
return view("index",compact("data"));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param \App\crud $crud
* @return \Illuminate\Http\Response
*/
public function show(crud $crud)
{
//
return "show";
}
/**
* Show the form for editing the specified resource.
*
* @param \App\crud $crud
* @return \Illuminate\Http\Response
*/
public function edit(crud $crud)
{
//
return "edit";
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\crud $crud
* @return \Illuminate\Http\Response
*/
public function update(Request $request,crud $crud)
{
//
return "update";
}
/**
* Remove the specified resource from storage.
*
* @param \App\crud $crud
* @return \Illuminate\Http\Response
*/
public function destroy(crud $crud)
{
//
return "destroy function is working";
}
}
路线
Route::resource('user/','CrudController');
解决方法
您的路线定义格式不正确。您要传递给第一个参数的是资源名称,它可以是URI,但最后一部分是资源名称。
Route::resource('user/',...);
这将在/
之后解释为资源名称,它将创建名为{}
的路由参数,为空白。尽管这会创建一个名称为show
的路由,因为没有资源名称可以添加到该路径。
正确的定义是:
Route::resource('user','CrudController');
这不会创建名为show
的路由。将会是user.show
。由于user
是资源名称。
在Controller中,参数为user
而不是crud
:
public function show(crud $user)
如果您确实愿意,可以覆盖使用的约定,但是我建议您坚持使用这些约定。如果需要,我可以覆盖这些内容。 [路由名称,路由参数名称...]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。