I am creating a web site and I have a Registration form. So , when someone going to use a username and email which is already in the database , I want to show them a message " Username and Email already taken " like this. If username and email are unique , user can register. But , when I try to register someone , it always shows " Username and Email already taken ". I can't register even when I use unique data.
How can I Fix this ??
AdminPanel.blade.php
#if(session()->has('OnlyImg'))
<h4 class="alert alert-success"> {{ session()->get('OnlyImg') }} </h4>
#endif
<form class="form-horizontal" method="POST" action="{{ route('adinsert') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label>Username : *</label>
<input type="text" class="form-control" name="username" value="{{ old('username') }}" placeholder="Enter Your Username" required>
</div>
<div class="form-group">
<label>Email : *</label>
<input type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Enter Your Username" required>
</div>
<div class="form-group">
<label>Password : *</label>
<input type="password" class="form-control" name="password" value="{{ old('password') }}" placeholder="Enter Your Password" required>
</div>
<div class="form-group">
<label>Upload Profile Picture :</label>
<input type="file" class="form-control-file" name="file_img" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">If U Want , U Can Skip Upload A Profile Picture</small>
</div>
#section('btnName',"Insert")
<input type="submit" class="btn btn-primary" onclick="myFunction()" name="submit" value="#yield('btnName')">
</form>
AdminPanelController.php
public function adinsert(Request $request)
{
$username = $request->input('username');
$email = $request->input('email');
$password = bcrypt($request->input('password'));
//$passen = bcrypt($password);
$user = new User();
$user->username = $username;
$user->email = $email;
$user->password = $password;
$this->validate($request, [
'email' => 'required'
]);
$res = DB::table('users')->where(['username' => $username, 'email' => $email])->get();
if ($res > 0 ) {
$request->session()->flash('Msg', 'Email already taken , Use another Email !!');
return redirect('AdminPanel');
}
else
{
if(Input::hasFile('file_img')){
$file = Input::file('file_img');
$rules = array(
'file_img' => 'required|max:10000|mimes:jpeg,png,jpg'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
$request->session()->flash('OnlyImg', 'You Can Only Upload Images !!');
return redirect('AdminPanel');
}
else if ($validator->passes()) {
$fileimg = $file->getClientOriginalName();
$destinationPath = 'img/Admins/';
$filemove = $file->move($destinationPath, $fileimg);
$user->fileimg = $fileimg;
$user->filemove = $filemove;
$user->save();
$request->session()->flash('Msg', 'Successfully Inserted !!');
return redirect('AdminPanel');
}
}
else
{
$user->save();
$request->session()->flash('Msg', 'Successfully Inserted !!');
return redirect('AdminPanel');
}
}
}
Here is Route.
Route::post('adinsert',[
'uses'=> 'AdminPanelController#adinsert',
'as' => 'adinsert'
]);
Related
Im new to laravel and i decided to make a little project to learn a bit and im trying to make a password reset function following this tutorial but the code seems to always update the first user no matter what. Even if user2#gmail.com tries to reset password, the password resets for user1#gmail.com.
Here is the code :
PasswordReset
public function forgotPassword(Request $request)
{
try {
$user = User::where('email', $request->email)->get();
if (count($user) > 0) {
$token = Str::random(40);
$domain = URL::to('/');
$url = $domain.'/reset-Password?token='.$token;
$data['url'] = $url;
$data['email'] = $request->email;
$data['title'] = "Password Reset";
$data['body'] = "Please click the link below to reset ur password";
Mail::send(
'forgetPasswordMail',
['data' => $data],
function ($message) use ($data) {
$message->to($data['email'])->subject($data['title']);
}
);
$datetime = Carbon::now()->format('Y-m-d H:i:s');
PasswordReset::updateOrCreate(
['email' => $request->email],
[
'email' => $request->email,
'token' => $token,
'created_at' => $datetime
]
);
return response()->json(['success' => true, 'msg' => 'Password Reset Sent']);
} else {
return response()->json(['success' => false, 'msg' => 'User not Found']);
}
} catch(\Exception $e) {
return response()->json(['success' => false, 'msg' => $e->getMessage()]);
}
}
public function resetPasswordLoad(Request $request)
{
$resetData = PasswordReset::where('token', $request->token)->first();
if ($resetData) {
$user = User::where('email', $resetData->email)->first();
if ($user) {
return view('resetPassword', ['user' => $user]);
}
}
return response()->json(['success' => false, 'msg' => 'error404']);
}
public function resetPassword(Request $request)
{
$request->validate([
'password' => 'required|string|min:6|confirmed',
'user_id' => 'required|integer'
]);
$user = User::find($request->user_id);
if ($user) {
$user->password = Hash::make($request->password);
$user->save();
PasswordReset::where('email', $user->email)->delete();
return "<h1>Password reset successfully</h1>";
} else {
return "<h1>Error: User not found</h1>";
}
}
view
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<center>
<form method="POST" action="/reset-Password">
#csrf
<input type="hidden" name="user_id" value="{{ $user->id }}">
<input type="password" name="password" placeholder="New Password">
<br>
<br>
<input type="password" name="password_confirmation" placeholder="Confirm Password">
<br>
<br>
<input type="submit">
</form>
</center>
I tried switching between using the token and email to authenticate but that just made the code a mess.
I am new in Laravel too. I started with it 3 months ago. I have to say, I was to much for me to do whole reset password logic on my own at this stage.
So in created new temp project with Breeze (https://laravel.com/docs/9.x/starter-kits#breeze-and-blade), and I tried to understand the reset password by debugging it step by step via xdebug.
Then I implemented same logic in my project and it is working like a charm.
public function forgotPassword(Request $request): RedirectResponse
{
$request->validate([
'email' => 'required|email',
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
if ($status == Password::RESET_LINK_SENT) {
return back()->with('success', __($status));
}
throw ValidationException::withMessages([
'email' => [trans($status)],
]);
}
public function resetPassword(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function ($user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('success', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
public function resetPasswordLoad(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
View reset-password.blade.php:
<form method="POST" action="{{ route('password.store') }}">
#csrf
<div class="mx-auto d-block w-100">
<p class="login-form-title py-3">{{__('login.reset_password_header')}}</p>
</div>
<!-- Password Reset Token -->
<input type="hidden" name="token" value="{{ $request->route('token') }}">
<div class="form-floating my-3">
<input type="text" class="form-control" id="email" name="email" placeholder="email" value="{{old('email', $request->email)}}">
<label for="email">{{__('user.email')}}</label>
#error('email')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<div class="form-floating my-3">
<input type="password" class="form-control" id="password" name="password" placeholder="Password" value="{{old('password')}}" required>
<label for="password">{{__('user.password')}}</label>
#error('password')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<div class="form-floating my-3">
<input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Repeat your password" value="{{old('password_confirmation')}}" required>
<label for="password_confirmation">{{__('user.repeat_your_password')}}</label>
#error('password_confirmation')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-block mb-4 w-100">{{__('generic.submit')}}</button>
<div class="text-center">
<p>{{__('login.back_to_login')}}</p>
</div>
</form>
View: forgot-password.blade.php
<form method="POST" action="{{route('password.email')}}">
#csrf
<div class="mx-auto d-block w-100">
<p class="login-form-title py-3">{{__('login.forgot_password_header')}}</p>
<p class="login-form-subtitle">
{{__('login.to_reset_your_password')}}
</p>
</div>
<div class="form-floating my-3">
<input type="text" class="form-control" id="email" name="email" placeholder="email" value="{{old('email')}}">
<label for="email">{{__('user.email')}}</label>
#error('email')
<span class="error-message">{{$message}}</span>
#enderror
</div>
<!-- Submit button -->
<button type="submit" class="btn btn-primary btn-block mb-4 w-100">{{__('generic.submit')}}</button>
<div class="text-center">
<p>{{__('login.back_to_login')}}</p>
</div>
</form>
I tried to edit and updated the employee info, unfortunately, it doesn't work
I fetch the employee id but when I sent the updated data it's not working.
it shows Requested URL not found on the server
this is my controller
public function edit_function($id){
$user = User::find($id);
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,$id){
$user = User::find($id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
this is my view
<form method="post" action="/updateimages/{{ $user->id }}" enctype="multipart/form-data">
<div class="container">
<div class="jumbotron">
<h2>Update The Information Of Employee</h2>
{{ csrf_field() }}
{{ method_field('PUT') }}
<div class="form-group">
<label >Name:</label>
<input type="text" class="form-control" id="name" placeholder="Enter Name" name="name" value="{{ $user->name }} ">
</div>
<div class="form-group">
<label >Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email" value="{{ $user->email }} ">
</div>
<div class="form-group">
<label >Phone Number:</label>
<input type="text" class="form-control" id="phonenumber" placeholder="Enter Phone Number" name="phonenumber" value="{{ $user->phonenumber }} ">
</div>
<div class="form-group">
<label >Profession :</label>
<input type="text" class="form-control" id="profession" placeholder="Enter Profession" name="profession" value="{{ $user->profession }} ">
</div>
<div class="form-group">
<label >Image :</label>
<input type="file" class="form-control" id="images" placeholder="" name="images" value="{{ $user->images }}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit" name="submit" style="width:50%;">Update Data</button>
</div>
</div>
</div>
</form>
this is my route
Route::get('edit_profile/{id}' , "empController#edit_function");
Route::put('/updateimages/{id}', "empController#update");
it shows Requested URL not found on the server
Since I am not a Big fan of Url and id So i will go with
name based routing and Route Model Binding
Step 1: Refactor Routes
Route::get('edit_profile/{user}' , "empController#edit_function")
->name('user.editProfile');
Route::put('/updateimages/{user}', "empController#update")
->name('user.updateProfile');
Step 2: Refactor Controller Method
public function edit_function(User $user)
{
$user = $user;
return view('employee.empedit')->with('user',$user);
}
public function update(Request $request,User $user)
{
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->phonenumber = $request->input('phonenumber');
$user->profession = $request->input('profession');
if($request->hasfile('images')){
$file= $request->file('images');
$extension = $file->getClientOriginalExtension();
$filename = time() . '.' . $extension;
$file->move('uploads/user/', $filename);
$user->images= $filename;
}
$user->save();
return redirect('empprofile')->with('success', 'Data Updated.');
}
Step 3: Edit Html and Switch to route helper
<form method="POST" action="{{route('user.updateProfile',['user' => $user])}}" enctype="multipart/form-data">
Kindly Comment Below if you are facing any issues
Its because some other route replce your existing route. You can solve it by debugging. it will cost your time. I had a better solution,
You name your route. and call the route by route() function.
From your above information,
It may be,
in route ->
Route::put('/updateimages/{id}', "empController#update")->name('updateImage');
in view (form action) ->
<form method="post" action="{{ route('updateImage', $user->id ) }}" enctype="multipart/form-data">
I am working with Laravel 5.6 and going to update My user table values (name,email,password) as the system admin.
blade file
<form action="{{route('users.update',$user->id)}}" method="POST">
{{method_field('PUT')}}
{{csrf_field()}}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{$user->name}}" >
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="{{$user->email}}">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="form-group">
<label for="password_confirmation">Confirm Password</label>
<input type="password" class="form-control" id="password_confirmation" name="password">
</div>
<button type="submit" class="btn btn-primary">Edit User</button>
</form>
and My controller,
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$user->name = $request->name;
$user->uservalue = $request->uservalue;
$user->email = $request->email;
$user->password = bcrypt($request->input('password'));
$user->save();
return view('users.show')->withUser($user);
}
Problem
my password confirmation is not working
That means I can enter password without confirmation and or wrong confirmation password. How can I fix this problem?
You have to add a password confirm validation. For that to work, your second password field has to be called password_confirmation (or foo and foo_confirmation)
public function update(Request $request, $id)
{
$user = User::findOrFail($id);
$request->validate([
'password' => 'sometimes|min:6|confirmed'
]);
$user->name = $request->name;
$user->uservalue = $request->uservalue;
$user->email = $request->email;
$user->password = bcrypt($request->input('password'));
$user->save();
return view('users.show')->withUser($user);
}
You can add more validation fields as explained here. If the validation fails, the browser will bring the user back to the update page. The errors are in the laravel errorbag available in your views as $errors.
sometimes means that the following rules are needed if there is an input. As you want to update user information, your visitors can leave the password field empty if they don't want to update the password. Unset the password field (if empty) before updating the user input.
I'm using Laravel 5.3. I'm trying to pass some input from the View to a Controller. Here is what I am doing now in the View:
<form class="form-horizontal" role="form" method="POST" action="{{ url('/update/company') }}">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Name</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus>
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
And here is the route:
Route::put('/update/company', [
'as' => 'updateCompany',
'uses' => 'Auth\RegisterController#update'
]);
And here is the Controller:
public function update(Request $request){
$compEmail = $this->companyEmail;
if( ! $compEmail)
{
echo "Email Invalid";
}
$user = User::all()->where("email", $compEmail)->first();
if ( ! $user)
{
echo "Invalid Company";
}
$user->name = $request->input('name');
$user->confirmed = 1;
$user->confirmation_code = null;
$user->save();
}
This is giving me the error:
Creating default object from empty value on the line $user->name =
$request->input('name');
Any tips?
If you haven't find any $user:
if ( ! $user) {
echo "Invalid Company";
}
you're not returning the method so here:
$user->name = $request->input('name');
$user->confirmed = 1;
$user->confirmation_code = null;
You try to access fields on null value from $user empty var.
You should add return here:
if ( ! $user) {
echo "Invalid Company";
return;
}
I want to create a register system, but i get this error:
Route [register] not defined. (View: C:\xampp\htdocs\system\app\views\account\register.blade.php)
Register.blade.php
#include('_base')
<div class="container">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create account</h3>
</div>
<div class="panel-body">
<form role="form" method="post" action="{{ URL::route('register') }}">
<div class="form-group">
<label for="firstname">firstname</label>
<input id="firstname" class="form-control" type="text" name="firstname" />
</div>
<div class="form-group">
<label for="lastname">lastname</label>
<input id="lastname" class="form-control" type="text" name="lastname" />
</div>
<div class="form-group">
<label for="password">password</label>
<input id="password" class="form-control" type="password" name="password" />
</div>
<div class="form-group">
<label for="email">E-mail adres</label>
<input id="email" class="form-control" type="text" name="email" />
</div>
<input type="submit" class="btn btn-success" value="Create" />
{{ Form::close() }}
</div>
</div>
</div>
</div>
#include('_end')
Routes
Route::post('account/register', 'AccounController#register');
And this is my Controller
<?php
Class AccountController extends BaseController {
public function getregister()
{
return View::make('account/register');
}
public function register()
{
$rules = array(
'firstname' => 'required',
'lastname' => 'required',
'password' => 'required|min:4',
'email' => 'required|unique:user'
);
$messages = array(
'firstname.required' => 'Voornaam is nodig',
'lastname.required' => 'Achternaam is nodig',
'password.required' => 'Er is een wachtwoord nodig',
'email.required' => 'Een e-mail adres is nodig',
'email.unique' => 'Dit e-mail adres bestaat al en kan geen 2x gebruikt worden'
);
$validator = Validator::make(Input::all(), $rules, $messages);
if($validator->fails())
{
return Redirect::to('register')
->withErrors($validate)
->withInput(Input::except('password'));
} else {
// Create User
$user = new User;
$user->firstname = Input::get('firstname');
$user->lastname = Input::get('lastname');
$user->password = Hash::make(Input::get('password'));
$user->email = Input::get('email');
$user->save();
Session::put('message', 'Je account is gemaakt');
}
}
}
Hope someone could help me
Edit url for form:
URL::to('accounts/register')
or add the name 'register' for route
Route::post('account/register', array('as'=>'register','uses'=>'AccountController#register');