#laravel
#laravel
Вопрос:
Я сгенерировал авторизацию пользователя через make:auth, в котором нет поля редактирования сведений, теперь я хочу отредактировать такие данные, как адрес электронной почты и контакт, а другие оставить отключенными. Я попытался скопировать код из RegisterController, я просто изменил метод create на метод update, если у вас есть готовый шаблон для редактирования деталей, пожалуйста, поделитесь мной, я искал много готовых шаблонов, но не нашел, мне просто нужен шаблон, который будет совместим с сгенерированным Auth или решением моей проблемы, потому что теперь онне обновляет детали
1) Просмотр: edit_profile.blade.php
<form method="POST" action="/profile">
@csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label>
<div class="col-md-6">
<input id="name" disabled type="text" class="form-control" value='{{$user->name}}' name="name">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-md-4 col-form-label text-md-right">{{ __('Student Number') }}</label>
<div class="col-md-6">
<input id="username" disabled type="text" class="form-control" name="username" value="{{$user->username}}">
</div>
</div>
<div class="form-group row">
<label for="age" class="col-md-4 col-form-label text-md-right">{{ __('Age') }}</label>
<div class="col-md-6">
<input id="age" disabled type="text" class="form-control" name="age" value="{{$user->age}}"
required> @if ($errors->has('age'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('age') }}</strong>
</span> @endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{$user->email}}"
required> @if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span> @endif
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-md-4 col-form-label text-md-right">{{ __('Contact Number') }}</label>
<div class="col-md-6">
<input id="contact" type="text" class="form-control{{ $errors->has('contact') ? ' is-invalid' : '' }}" name="contact" value="{{$user->contact}}"
required> @if ($errors->has('contact'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('contact') }}</strong>
</span> @endif
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Update Details') }}
</button>
</div>
</div>
</form>
2) Контроллер: ProfileController
<?php
namespace AppHttpControllers;
use Auth;
use IlluminateHttpRequest;
use Image;
use AppUser;
use AppHttpControllersController;
use IlluminateSupportFacadesValidator;
use IlluminateFoundationAuthRegistersUsers;
use IlluminateSupportCarbon;
class ProfileController extends Controller
{
public function profile(){
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
public function update_avatar(Request $request){
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->crop(300, 300)->save( public_path('/storage/images/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return view('pages.profiles.profile', array('user' => Auth::user()) );
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255|unique:users',
'contact' => 'numeric|digits_between:7,15',
]);
}
public function edit(){
return view('pages.profiles.edit_profile', array('user' => Auth::user()) );
}
public function update(array $data){
return User::update([
'email' => $data['email'],
'contact' => $data['contact'],
]);
}
}
Маршруты
//User Profile
Route::get('/profile', 'ProfileController@profile');
Route::post('profile', 'ProfileController@update_avatar');
Route::get('/profile/edit', 'ProfileController@edit');
Route::post('profile/edit', 'ProfileController@update');
Комментарии:
1. В чем проблема? Вы получаете сообщение об ошибке?
2. @RossWilson Это просто не обновило данные, ошибок нет
Ответ №1:
Есть несколько проблем, которые я заметил.
- Ваш
ProfileController@update
метод принимает массив, но ему не будет передан массив. - Вы не вызываете
update
аутентифицированного пользователя. - Вы отправляете сообщение, в
/profile
котором просматриваете свои маршруты, если для обновления аватара, а не пользовательских данных.
Измените свою форму на:
<form method="POST" action="/profile/edit">
Измените свой update
метод на:
public function update(Request $request)
{
$data = $this->validate($request, [
'email' => 'required|email',
'contact' => 'required',
]);
auth()->user()->update($data);
return auth()->user();
}
Ответ №2:
public function update(Request $request)
{
//check validation
Auth::user()->update($request);
return true;
}