如何限制仅在laravel索引中显示数据时进行编辑
我的edit.blade.php有问题。在show视图中,我仅对用户的登录进行了限制,您可以在我的控制器中看到这一点如何限制仅在laravel索引中显示数据时进行编辑,laravel,Laravel,我的edit.blade.php有问题。在show视图中,我仅对用户的登录进行了限制,您可以在我的控制器中看到这一点 public function index() { $animal = Auth::user()->animals; return view('farms.index', compact('animal')); } 还有我的索引视图 @extends('layouts.app') @section('content')
public function index()
{
$animal = Auth::user()->animals;
return view('farms.index', compact('animal'));
}
还有我的索引视图
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Farm Dashboard</div>
<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif
You are logged in! {{ Auth::user()->name }}
<br>
<a href="farms/create">Add animal</a>
@foreach( $animal as $animal)
<div class="row">
<div class="col-2">{{ $animal->id }}</div>
<div class="col-4"><a href="/farms/{{ $animal->id }}">{{ $animal->type->category }}</a></div>
<div class="col-4">{{ $animal->created_at }}</div>
</div>
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
你可以遵循这个基本/简单的方法 作秀
public function show($id)
{
try {
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
return view('farms.show', compact('animal'));
} catch(\Exception $ex) {
//return exception or any other page
abort(404, 'Not allowed');
//or return back()->withErrors(['Not allowed']);
}
}
编辑
public function edit($id)
{
try {
$type = Type::all();
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
return view('farms.edit', compact('animal', 'type', 'user'));
} catch(\Exception $ex) {
//return exception or any other page
}
}
更新
public function update($id)
{
try {
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
$animal->update($this->validateRequest());
return redirect('farms/' . $animal->id)->with('message', 'Animal Details Updated'); //use route for redirect instead of url
} catch(\Exception $ex) {
//return exception or any other page
}
}
使用try catch
获取异常
确保您已定义该动物具有user\u id
或
您还可以使用关系管理此功能
对于标准实践,您可以使用laravel门策略
这是我收到的错误“Symfony\Component\Debug\Exception\FatalThrowableError调用成员函数findOrFail(),返回null”使用try catch块处理异常对不起,我对laravel还是新手,所以我不知道;我不知道如何使用catch块来处理laravely中的错误。您的错误似乎是试图访问null对象上的某些内容。再看一次,它应该会起作用。如果没有,请在此处或聊天室中共享您的代码
public function update($id)
{
try {
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
$animal->update($this->validateRequest());
return redirect('farms/' . $animal->id)->with('message', 'Animal Details Updated'); //use route for redirect instead of url
} catch(\Exception $ex) {
//return exception or any other page
}
}