Reset password manually via answering the security questions without sending email - Laravel/auth - laravel

I am currently developing a simple Bookstore application with a few numbers of users on which sending emails are not needed because it will be implemented in local system so is there any way to customize laravel-auth for password reset function by adding a few security questions fields where user can reset his/her password without sending reset links via email.
Any kind of help will be highly appreciated.
here I tried the below code but id did not work
Code in web.php
Route::post('/main/checklogin', 'UserController#chekQuestions');
Code in userContoller
public function chekQuestions(Request $request)
{
$request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::first();
if($user->email == $request->email && $user->answerQuestionOne == $request->answerQuestionOne && $user->answerQuestionTwo == $request->answerQuestionTwo )
{
// $userEmail = DB::table( 'password_resets' )->where( 'token', $user->token );
// return view('auth.password.reset',compact($userEmail));
return view('auth.password.reset');
}
return response()->json( [
'error' => true,
'message' => 'We cannot find a user with that Email Address'
], 404 );
}
Code in reset password.blade
<div id="register" class="animate form registration_form">
<section class="login_content">
<form method="POST" action="{{ url('/main/checklogin') }}" >
#csrf
<h3>د پټ نو بیا راګرځولو لپاره لاندی امنتی پوښتنو ته ځواب ورکړی </h3>
<div class="form-group has-feedback">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
<div class="form-control-feedback">
<i class="fa fa-envelope-o text-muted"></i>
</div>
</div>
<div>
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div>
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<button type="submit" class="btn btn-default btn-block">خوندی کړی </button>
<div class="clearfix"></div>
<div class="separator">
<p class="change_link">
تاسو دمخه غړی یاست ننوتل
</p>
<div class="clearfix"></div>
<br />
</form>
</section>
</div>

You don't need Laravel implementation for this. Just Find a user with the given email and check the answers. After that update the user record with the new password.
In order to fetch user you should do this:
$data = $request->validate( [
'email' => 'required|string|email',
'answerQuestionOne' => 'required|string|confirmed',
'answerQuestionTwo' => 'required|string'
] );
$user = User::where(['email' => $data['email'])->first();
After this just check the answers.
You also need to take the new password from user.

Related

Frontend form Laravel Nova

I really like Laravel Nova but it's really complicated for a newbie like me to do something on the frontend that interacts with backend resources.
Can anyone tell me how to make a form insert data into a table from the frontend? Do I need to create a new external model? Can't interact with Nova resources?
Thanks in advance for enlightening me.
My form:
<form wire:submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" id="code" placeholder="Introduzca código " name="code">
#error('code') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="ip" placeholder="Introduzca IP " name="ip">
#error('ip') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<div class="form-group">
<input type="text" class="form-control" id="access" placeholder="Introduzca access " name="access">
#error('access') <span class="text-danger">{{ $message }}</span> #enderror
</div><br>
<button type="submit" class="btn btn-block btn-primary">Crear Asistencia</button>
</form>
My function submit:
public function submit()
{
$this->validate([
'code' => 'required|min:4',
'ip' => 'required|min:15',
'access' => 'required|min:1',
]);
Attendance::create([
'code' => $this->code,
'ip' => $this->ip,
'access' => $this->access,
]);
session()->flash('message','asistencia creada correctamente');
return redirect(RouteServiceProvider::HOME);
}

Reset password manually by answering the security questions - Laravel

I want to implement locally forgot password functionality by answering a few security questions where user can reset his/her password without sending reset links via emails.
Here I have tried the below code, in updatePassword.blade.php the email, password, and password-confirm validation is not working so I implement it in the UserControler when I put the email address which is not in the database, or when I put the miss-matched password in the password and password-confirm inputs it throws the below error, but if I put the correct email and password with the matched password in the password and password-confirm inputs it resets my password, I don't know what is wrong.
Any kind of help will be highly appreciated.
ErrorException (E_ERROR) Trying to get property of non-object (View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
(View:
C:\xampp\htdocs\Bookstore\resources\views\layouts\layout.blade.php)
Here are routes in web.php
Route::get('getview', [
'uses' => 'HomeController#getview',
'as' => 'check.getview'
]);
Route::post('chekQuestions', [
'uses' => 'HomeController#chekQuestions',
'as' => 'check.question'
]);
Route::post('updagePassword', [
'uses' => 'HomeController#updagePassword',
'as' => 'update.question'
]);
Here is the code in Controller
public function getview()
{
return view('auth.test');
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
return redirect()
->back()
->with(Session::flash('message2', 'ځواب مو مطابقت نلری'))
->withInput();
}
if ($user->answerQuestionTwo != $request->answerQuestionTwo) {
return redirect()
->back()
->with(Session::flash('message3', 'ځواب مو مطابقت نلری'))
->withInput();
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|confirmed|min:8'
]);
$user = User::first();
if ($user->email != $request->email) {
return redirect()
->back()
->with(Session::flash('message', 'دا ایمل شتون نلری'))
->withInput();
} elseif ($request->password_confirmation != $request->password) {
return redirect()
->back()
->with(Session::flash('message2', 'دا ایمل شتون نلری'))
->withInput();
} else {
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}
}
Here is the link going to the test view
<a style="font-size: 15px;" href="{{route('check.getview')}}" class="to_register">د پټ نو بیا راګرځول د امنتی پوښتنو له لاری </a>
Here test view
<div class="x_content">
<br>
<form method="POST" action="{{route('check.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="last-name">
لومړۍ امنیتي پوښتنه <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionOne" placeholder="لومړۍ امنیتي پوښتنه" type="text" class="form-control #error('answerQuestionOne') is-invalid #enderror" name="answerQuestionOne" value="{{ old('answerQuestionOne') }}" required autocomplete="answerQuestionOne" autofocus>
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('answerQuestionOne')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="form-group">
<label for="middle-name" class="control-label col-md-3 col-sm-3 col-xs-12">
دوهمه امنیتي پوښتنه </label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="answerQuestionTwo" placeholder="دوهمه امنیتي پوښتنه " type="text" class="form-control #error('answerQuestionTwo') is-invalid #enderror" name="answerQuestionTwo" value="{{ old('answerQuestionTwo') }}" required autocomplete="answerQuestionTwo" autofocus>
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
#error('answerQuestionTwo')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror </div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
Here is the updatePassword.blade.php
<div class="x_content">
<br>
<form method="POST" action="{{route('update.question')}}" class="form-horizontal form-label-left">
#csrf
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">ایمل
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- #foreach ($user as $getemail) --}}
{{-- value="{{ old('email') }}" --}}
<input id="email" type="email" placeholder=" ایمل" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $user->email }}" required autocomplete="email" autofocus>
{{-- #endforeach --}}
#if(Session::has('message'))
<p class="bg-danger">{{session('message')}} </p>
#endif
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ نوم
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#if(Session::has('message2'))
<p class="bg-danger">{{session('message2')}} </p>
#endif
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">پټ تأیید
<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{{-- <input id="passwordconfirm" type="password" class="form-control" name="passwordconfirm" required autocomplete="new-password">
--}}
<input id="password-confirm" type="password" placeholder="دپټنوم تأیید " class="form-control" name="password_confirmation" required autocomplete="new-password">
#if(Session::has('message3'))
<p class="bg-danger">{{session('message3')}} </p>
#endif
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
{{-- <button type="submit" class="btn btn-primary">انصراف</button> --}}
<button type="submit" class="btn btn-success">خوندی کړی</button>
</div>
</div>
</form>
</div>
try this
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
]);
I found the solution by manually setting the validation messages
Code in the controller
public function getview(Request $request)
{
$user=new User();
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
return view('auth.question',compact('user','anserone','anstwo'));
}
public function chekQuestions(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'answerQuestionOne' => 'required',
'answerQuestionTwo' => 'required'
]);
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionOne == null || $user->answerQuestionTwo == null) {
//
$user=new User();
$user->email= $request->email;
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message4', 'هیڅ مورد نشته، لمړی تاسی خپل امنیتی ځوابونه خوندی کړی');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ($user->answerQuestionOne != $request->answerQuestionOne) {
$anserone= $request->answerQuestionOne;
$anstwo = $request->answerQuestionTwo;
Session::flash('message2', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anserone','anstwo'));
}
if ( $user->answerQuestionTwo != $request->answerQuestionTwo) {
$anstwo = $request->answerQuestionTwo;
$anserone= $request->answerQuestionOne;
Session::flash('message3', 'دپښتنو ځوابونه مو ناسم وو');
return view('auth.question',compact('user','anstwo','anserone'));
}
return view('auth.updatePassword',compact('user'));
}
public function updagePassword(Request $request)
{
$this->validate($request, [
'email' => 'required|string|email',
'password' => 'required|min:8'
]);
// $user = User::first();
$user = User::where('email', $request->email)->first();
if ( $user == null) {
//
$user=new User();
$user->email= $request->email;
// $anserone= $request->answerQuestionOne;
// $anstwo = $request->answerQuestionTwo;
Session::flash('message', 'دا ایمل شتون نلری');
return view('auth.updatePassword',compact('user'));
}
if ($request->password_confirmation != $request->password) {
Session::flash('message3', 'پټ نوم مطابقت نلری');
return view('auth.updatePassword',compact('user'));
}
$user->where('email', $request->email)->update([
'password' => Hash::make($request->password)
]);
return redirect()->route('login');
}

Default password in Laravel

I would like to configure a default password because in the project I am working on, It is the admin who is to create accounts for users.
Of course, if a put a default value on my model, It will not hash the password. How else can I approach this
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('POBox');
$table->string('password');
$table->rememberToken();
$table->unsignedBigInteger('address_id')->index();
$table->unsignedInteger('role_id');
$table->timestamps();
$table->foreign('address_id')->references('id')->on('addresses');
});
}
Have the Admin only create the user and then email the New user a password reset.
Form:
<form method="POST" action="{{ route('admin.user.store') }}" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
#csrf
<div class="form-group">
<div class="row">
<div class="col-md-6">
<label for="first_name" class="no-pad-left col-form-label white-txt muli w4">First Name</label>
<input id="first_name" type="text" class="form-control{{ $errors->has('first_name') ? ' is-invalid' : '' }}" name="first_name" placeholder="Enter First Name" value="{{ old('first_name') }}" required autofocus>
#if ($errors->has('first_name'))
<span class="invalid-feedback appearance-none block w-full bg-gray-200 text-gray-700 border border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white">
<strong>{{ $errors->first('first_name') }}</strong>
</span>
#endif
</div>
<div class="col-md-6">
<label for="last_name" class="no-pad-left col-form-label white-txt muli w4">Last Name</label>
<input id="last_name" type="text" class="form-control{{ $errors->has('last_name') ? ' is-invalid' : '' }}" name="last_name" placeholder="Enter Last Name" value="{{ old('last_name') }}" required autofocus>
#if ($errors->has('last_name'))
<span class="invalid-feedback appearance-none block w-full bg-gray-200 text-gray-700 border border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white">
<strong>{{ $errors->first('last_name') }}</strong>
</span>
#endif
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label for="email" class="no-pad-left col-form-label white-txt muli w4">E-Mail Address</label>
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" placeholder="Enter Email Address" value="{{ old('email') }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback appearance-none block w-full bg-gray-200 text-gray-700 border border-red-500 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
</div>
<div class="flex">
<button type="submit" class="bg-yellow-500 hover:bg-yellow-700 text-navy-500 md:w-1/4 sm:w-full w-full font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline shadow-lg" type="button">
Create User
</button>
</div>
</form>
Controller
public function adminUserStore(Request $request){
$validatedData = $request->validate([
'first_name'=> 'required|string|max:255',
'last_name'=> 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
]);
$quickpass = substr( str_shuffle( str_repeat( 'abcdefghijklmnopqrstuvwxyz0123456789', 10 ) ), 0, 10 );
$adminName = Auth::user()->first_name.' '.Auth::user()->last_name;
$newuser = User::create([
'first_name'=> $request->first_name,
'last_name'=> $request->last_name,
'email' => $request->email,
'password' => Hash::make($quickpass),
'role_id' => '0',
'added_by' => $adminName,
]);
Mail::to($newuser->email)
->send(new NewUserPassReset(
$request->input('first_name'),
$request->input('last_name'),
$request->input('email')
));
return back()->with('success','The user has been created and a password reset email has been sent to them.');
}
You should be able to figure out the email part. Then in the email that is sent to the new user, include a link to the Reset Password route.
That's how I do it.
You can use default values in a Model.
User.php
public class User extends Model
{
protected $attributes = [
'password' => Hash::make(Str::random(40))
];
}
Str::random will give you a random 40-chars String. You can change this to anything you like.
Hash::make() will hash the String so Laravel can check the Hash when User tries to login.

How to change password?

I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}

Laravel always sets the default value

I am trying to do registration with user profile picture upload.(I am forced to do it this way)
I created the migration like this:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('nom');
$table->string('prenom');
$table->string('type')->default('visiteur');
$table->boolean('confirme')->default(false);
$table->string('email')->unique();
$table->string('password');
$table->string('photo_url')->default('default_photo_profile.jpg');
$table->rememberToken();
$table->timestamps();
});
the create function :
$request = request();
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
and the form for the file field is like this:
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
everything is working fine except the photo_url field, it always sets the default value in the migration and not the value I set in the create function.
$fullname is initiated and already declared.
the entire form :
<form method="POST" action="{{ route('register') }}" aria-label="{{ __('Register') }}" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<label for="nom" class="col-md-4 col-form-label text-md-right">Nom</label>
<div class="col-md-6">
<input id="nom" type="text" class="form-control{{ $errors->has('nom') ? ' is-invalid' : '' }}" name="nom" value="{{ old('nom') }}" required autofocus>
#if ($errors->has('nom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="prenom" class="col-md-4 col-form-label text-md-right">Prénom</label>
<div class="col-md-6">
<input id="prenom" type="text" class="form-control{{ $errors->has('prenom') ? ' is-invalid' : '' }}" name="prenom" value="{{ old('prenom') }}" required autofocus>
#if ($errors->has('prenom'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('prenom') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">Email</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('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="password" class="col-md-4 col-form-label text-md-right">Mot de pass</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">Mot de pass confirmation</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>
</div>
</div>
<div class="form-group">
<label for="photo_url">Photo profile</label>
<input type="file" name="photo" class="form-control-file" id="photo_url">
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Envoyer
</button>
</div>
</div>
</form>
What is the problem?
Assuming you have a value for $photo_url, make sure you have 'photo_url' in your $fillables.
When you have $fillables, it only inserts (via User::create) what has in that array, otherwise it doesn't submit for that variable.
Your $fillables should look like this:
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
Add 'photo' in $fillable array in User model:
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'photo_url',
];
so according to your code in your model you have to add the photo_url in $fillable array like below.
$fillables = ['nom','prenom','type','confirme','email','password','photo_url'];
okay now there are 3 ways to do it with $fillable is first way and you are doing it right now.
2nd way:
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
}
else
{
$fullname = "default_photo_profile.jpg";
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
and in your migration change this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
3rd way:
$fullname = "default_photo_profile.jpg";
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$fullname=$data['nom'].'_'.date("Y-m-d",time()).'.'.$file->getClientOriginalExtension();
$path = $request->file('photo')->storeAs('images', $fullname);
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
return User::create([
'nom' => $data['nom'],
'prenom' => $data['prenom'],
'email' => $data['email'],
'photo_url' => $fullname,
'password' => Hash::make($data['password']),
]);
}
okay these are the ways to do it. i would prefer first and second way 3rd one is lengthy.
Note: for 2nd and 3rd case you have to change your migration from this $table->string('photo_url')->default('default_photo_profile.jpg'); to $table->string('photo_url');
Hope you get it.

Resources