laravel hyn/multi-tenancy override login method using tenant db redirect again login page try to redirect homepage - laravel

In hyn/multi-tenancy after overriding the login method in LoginController and within this method connect the tenant database. It login successfully if I print the login results but when I redirect it to homeController it again redirects to the Login Page and doesn't go to the home page. I use
https://github.com/peartreedigital/boilerplate
example only change in loginController which is
class LoginController extends Controller
{
use AuthenticatesUsers;
public function username()
{
$login = request()->input('identity');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
request()->merge([$field => $login]);
return $field;
}
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function validateLogin(Request $request)
{
$messages = [
'identity.required' => 'Email or username cannot be empty',
'email.exists' => 'Email or username already registered',
'username.exists' => 'Username is already registered',
'password.required' => 'Password cannot be empty',
];
$request->validate([
'identity' => 'required|string',
'password' => 'required|string',
'email' => 'string|exists:users',
'username' => 'string|exists:users',
], $messages);
$domain_name = $request->get('domain_name');
$usernameatacc = $request->get('identity');
$password = $request->get('password');
$hostname = DB::table('hostnames')->select('*')->where('fqdn', $domain_name)->first();
$dbname = DB::table('websites')->select('uuid')->where('id', $hostname->website_id)->first();
Config::set("database.connections.tenant", [
"driver" => 'mysql',
"host" => '127.0.0.1',
"database" => $dbname->uuid,
"username" => 'root',
"password" => ''
]);
Config::set('database.default', 'tenant');
DB::purge('tenant');
DB::reconnect('tenant');
}
public function login(Request $request)
{
$this->validateLogin($request);
$user_data = User::where('email', $request->get('identity'))
->first();
$matchPwd = Hash::check($request->get('password'), $user_data->password);
if ($matchPwd == '1') {
// print_r($user_data);
// Here What can I do????? Please help
}else {
return redirect()->back()->withErrors($user_data);
}
}
protected function guard()
{
return Auth::guard();
}
}
My login form in login.blade.php is
<form method="POST" action="{{ route('login') }}">
#csrf
<div class="form-group row">
<label for="domain_name" class="col-sm-4 col-form-label text-md-right">{{ __('Domain Name') }}</label>
<div class="col-md-6">
<input id="domain_name" type="domain_name" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="domain_name" value="{{ old('domain_name') }}" required autofocus>
#if ($errors->has('domain_name'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('domain_name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-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="identity" value="{{ old('email') }}" required autofocus>
#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">{{ __('Password') }}</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">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>

You can redirect user after login with defining either method of redirectTo() or property of $redirectTo.
protected function redirectTo()
{
if (User::check()) {
return route('home');
}
}
or
protected $redirectTo = '/';
Be careful about referring to the name that you've assigned in the route file (default: web.php).

Related

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');
}

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'));
}

I have generated User Login and Register through make:auth, now i want to update details

I have generated user auth through make:auth, which doesn't have edit details field, now I want to edit details such as email and contact, and others leave as disabled. I have tried to copy code from RegisterController i just changed create method to update method, If you have ready template for edit details please share me, I have searched many ready templates but not found, I just want template, which will be compatible with generated Auth or solution to my problem, because now it is not updating the details
1) View: 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) Controller: ProfileController
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use Image;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Carbon;
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'],
]);
}
}
Routes
//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');
There are a few issues that I've noticed.
You're ProfileController#update method accepts an array but it won't be getting passed an array.
You're not calling update on the authenticated user.
You're posting to /profile which looking at your routes if for updating the avatar and not the user data.
Change your form to be:
<form method="POST" action="/profile/edit">
Change your update method to:
public function update(Request $request)
{
$data = $this->validate($request, [
'email' => 'required|email',
'contact' => 'required',
]);
auth()->user()->update($data);
return auth()->user();
}
Documentation for Laravel's Validation
public function update(Request $request)
{
//check validation
Auth::user()->update($request);
return true;
}

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.

Laravel PHPUnit Test Undefined Errors Variable

I would like someone to explain to me why I'm getting undefined variable errors when I run my phpunit tests from my Laravel application. I have if statements set up so that it doesn't add them by default so not sure why.
<?php
Route::auth();
Route::group(['middleware' => 'web'], function () {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => 'HomeController#dashboard']);
});
<form role="form" method="POST" action="{{ url('/login') }}">
{{ csrf_field() }}
<div class="form-group form-material floating {{ $errors->has('email') ? 'has-error' : '' }}">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}"/>
<label for="email" class="floating-label">Email</label>
#if ($errors->has('email'))
<small class="help-block">{{ $errors->first('email') }}</small>
#endif
</div>
<div class="form-group form-material floating {{ $errors->has('password') ? 'has-error' : '' }}">
<input id="password" type="password" class="form-control" name="password" />
<label for="password" class="floating-label">Password</label>
#if ($errors->has('password'))
<small class="help-block pull-left">{{ $errors->first('password') }}</small>
#endif
</div>
<div class="form-group clearfix">
<div class="checkbox-custom checkbox-inline checkbox-primary checkbox-lg pull-left">
<input type="checkbox" id="inputCheckbox" name="remember">
<label for="inputCheckbox">Remember me</label>
</div>
<a class="pull-right" href="{{ url('/password/reset') }}">Forgot password?</a>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg margin-top-40">Log in</button>
</form>
<?php
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class LoginTest extends TestCase
{
use WithoutMiddleware;
/** #test */
public function user_can_visit_login_page()
{
$this->visit('login');
}
/** #test */
public function user_submits_form_with_no_values_and_returns_errors()
{
$this->visit('login')
->press('Log in')
->seePageIs('login')
->see('The email field is required.')
->see('The password field is required.');
}
/** #test */
public function it_notifies_a_user_of_wrong_login_credentials()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type('notmypassword', 'password')
->press('Log in')
->seePageIs('login');
}
public function user_submits_login_form_unsuccesfully()
{
$user = factory(App\User::class)->create([
'email' => 'john#example.com',
'password' => 'testpass123'
]);
$this->visit('login')
->type($user->email, 'email')
->type($user->password, 'password')
->press('Log in')
->seePageIs('dashboard');
}
}
Errors Given
1) LoginTest::user_can_visit_login_page
A request to [http://myapp.app/login] failed. Received status code [500].
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:196
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:80
/Users/me/Projects/repositories/MyApp/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithPages.php:61
/Users/me/Projects/repositories/MyApp/tests/LoginTest.php:13
Caused by
exception 'ErrorException' with message 'Undefined variable: errors' in /Users/me/Projects/repositories/MyApp/storage/framework/views/cca75d7b87e55429621038e76ed68becbc19bc14.php:30
Stack trace:
Remove the WithoutMiddleware trait from your test.

Resources