我目前正在学习Laravel 5.8并创建instagram clone应用,并且在更新个人资料详细信息时遇到了问题。每当我点击“更新配置文件”时,都会发出错误-“在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}");
}
}
谢谢您!
尝试传递您正在编辑的用户,因为您已经在路由中传递了他们。,该错误表示您想更新一个用户,但尚未指定要更新的用户。尝试做这样的事情:
public function validateUser(){
return request()->validate([
'title' => 'required',
'description' => 'required',
'photo' => '',
]);
}
然后在更新功能中执行以下操作:
public function update($user_id){
return User::where('id',$user_id)->update($this->validateUser());
}
更新或插入
有时,如果不存在匹配的记录,您可能希望更新数据库中的现有记录或创建它。在这种情况下,可以使用updateOrInsert
方法。
User::where('id',$id)->updateOrInsert($data);