【发布时间】:2020-10-04 00:59:14
【问题描述】:
我目前正在学习 Laravel 5.8 并创建 Instagram 克隆应用程序,但在更新我的个人资料详细信息时遇到了问题。每当我点击“更新配置文件”时,它都会发出一个错误 - “在 null 上调用成员函数 update()”。问题似乎出在公共函数 update() 中。我查看了其他线程,似乎无法解决此问题,因此将不胜感激!
这是我的代码:
查看:
@section('content')
<div class="container">
<form action="/profile/{{ $user->id }}" enctype="multipart/form-data" method="post" >
@csrf
@method('PATCH')
<div class="row">
<div class="col-8 offset-2">
<div class="row pb-3">
<h1>Edit profile</h1>
</div>
<div class="form-group row">
<label for="title" class="col-form-label"><strong>Title</strong></label>
<input id="title" type="text" class="form-control @error('title') is-invalid @enderror" name="title" value="{{ old('title') ?? $user->profile['title'] }}" required autocomplete="title" autofocus>
@error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $title }}</strong>
</span>
@enderror
</div>
<div class="form-group row">
<label for="description" class="col-form-label"><strong>Description</strong></label>
<input id="description" type="text" class="form-control @error('description') is-invalid @enderror" name="description" value="{{ old('description') ?? $user->profile['description']}}" required autocomplete="description" autofocus>
@error('description')
<span class="invalid-feedback" role="alert">
<strong>{{ $description }}</strong>
</span>
@enderror
</div>
<div class="row">
<label for="photo" class="col-form-label">Select Profile Picture</label>
<input type="file" class="form-control-file" id="photo" name="photo">
@error('photo')
<strong>{{ $message }}</strong>
@enderror
</div>
<div class="row pt-3">
<button class="btn btn-primary">
Update Profile
</button>
</div>
</div>
</div>
</form>
</div>
@endsection
路线:
Auth::routes();
Route::get('/profile/{user}', 'ProfileController@index')->name('profile.show');
Route::get('/profile/{user}/edit', 'ProfileController@edit')->name('profile.edit');
Route::patch('/profile/{user}', 'ProfileController@update')->name('profile.update');```
控制器:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProfileController extends Controller
{
public function index(User $user){
return view('profile.index', [
'user' => $user,
]);
}
public function edit(User $user){
return view('profile.edit', [
'user' => $user,
]);
}
public function update(User $user){
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
auth()->user()->profile->update($data);
return redirect("/storage/ {$user->id}");
}
}
提前谢谢你!
【问题讨论】:
-
如果您通过 URL 传递用户来表示您要编辑哪条记录,那么您为什么还要尝试使用当前经过身份验证的用户?
-
将
action="/profile/{{ $user->id }}"更改为action="{{ route('profile.update', ['user' => $user->id]) }}" -
你需要在更新表上找到id,然后你才能更新它
标签: php laravel controller laravel-5.8