I'm having a difficulty to change the current user's email to a new email which is user input and the email's validation. EDITED
Here's my controller
public function changeuser(Request $request){
$id = Auth::user()->id;
$change_user = User::find($id);
$valid = validator($request->only('oldpass', 'newpass', 'confirmpass'), [
'olduser' => 'required|email|max:255|exists:users',
'newuser' => 'required|email|max:255|different:olduser'
], [
'newuser.required_with' => 'Choose different email.'
]);
if ($valid->fails()) {
return redirect('/manageaccount')->with('message','Failed to update email');
}
$change_user->email = $request->input('newuser');
$change_user->save();
return redirect('/manageaccount')->with('message', 'email changed successfully');
}
my blade.php which is in modal
<div class="thirdea" id="thirdea">
<label><p class="small Montserrat">Enter Old Username</p></label>
<input type="text" class="form-control small Montserrat" name="olduser" value="" id="olduser">
<label><p class="small Montserrat"> New Username</p></label>
<input type="text" class="form-control small Montserrat" name="newuser" value="" id="newuser">
</div>
my route
Route::post('/changeuser/','UserController#changeuser');
In case of update user you can try validations for email like this :
$validate = $request -> validate([
'newuser' => 'required|unique:users,email,'.$user->id
]);
Related
I have a webpage with 4 different urls
www.sample.com\home
www.sample.com\about
www.sample.com\products
www.sample.com\contact
I have a contact form in all the pages of my webpage.
I need to know the Page, from where the contact form is submitted from either(home, about, products or services).
I use laravel mailer to send mail, once the contact form is submitted.
Contact form:
<input type="hidden" name="url" value="{{substr(strrchr(url()->current(),'/'),1)}}">
<form method="POST" action="sendEmail">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="{{ old('name') }}" />
<label for="email">Email</label>
<input type="email" name="email" id="email" value ="{{ old('email') }}"/>
<label for="message">Message</label>
<textarea name="body" id="message" rows="5"> {{ old('message') }}</textarea>
<button class ="primary"> Submit </button>
</form>
Controller:
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = PostRequest::input('url');
\Mail::send('E-mail view', $data, $currentPage, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}
I need the URL as home, about, products, contact, from where the Contact form is submitted from not the form action sendEmail inside the E-mail View blade file
Email View Blade:
<p> $name </p>
<p> $email</p>
<p> $currentPage </p>
It throws an Error
Function name must be a string
How to pass the current URL from Where the Form is submiited from (home, about,..) to Mail?
Could anyone please help?
Many thanks.
Try like this
use Illuminate\Support\Facades\Request as PostRequest;
public function store()
{
$data = request()->validate([
'name' => 'required',
'email' => 'required|email',
'body' => 'required'
]);
// To get the current URL
$currentPage = request()->url();
$data['currentPage'] = $currentPage;
\Mail::send('E-mail view', $data, function($message) use ($data, $currentPage){
$message->to('abc#xyz.com')
->from($data['email'], $data['name'])
->replyTo($data['email'], $data['name'])
->returnPath($currentPage)
->subject('Notification');
});
return back();
}
form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I'm currently trying to make change password functionality to my user profile all my inputs are submitted to the controller, but I think there might be something wrong with my function logic maybe?
Tried dumping request on function and dump was successfully returned. But when wrapping a validation variable around a validation process, the dump was not returned. The request redirects back to the profile page with form data.
Controller
public function updatePassword(Request $request)
{
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
$user = User::find(Auth::id());
if (!Hash::check($request->current, $user->password)) {
return response()->json(['errors' =>
['current' => ['Current password does not match']]], 422);
}
$user->password = Hash::make($request->password);
$user->save();
return $user;
}
View
<form method="POST" action="{{ route('update-password') }}">
#csrf
#method('PUT')
<div class="form-group row">
<label for="old_password" class="col-md-2 col-form-label">{{ __('Current password') }}</label>
<div class="col-md-6">
<input id="old_password" name="old_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="new_password" class="col-md-2 col-form-label">{{ __('New password') }}</label>
<div class="col-md-6">
<input id="new_password" name="new_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="password_confirm" class="col-md-2 col-form-label">{{ __('Confirm password') }}</label>
<div class="col-md-6">
<input id="password_confirm" name="password_confirm" type="password" class="form-control" required
autofocus>
</div>
</div>
<div class="form-group login-row row mb-0">
<div class="col-md-8 offset-md-2">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>
The result should return 422/error message at least into the console when 'Current password' is wrong, not just redirect back to view and when the password is correct then return 200/success message (not implemented yet.) to console or view.
try this
public function updatePassword(Request $request){
if (!(Hash::check($request->get('old_password'), Auth::user()->password))) {
// The passwords not matches
//return redirect()->back()->with("error","Your current password does not matches with the password you provided. Please try again.");
return response()->json(['errors' => ['current'=> ['Current password does not match']]], 422);
}
//uncomment this if you need to validate that the new password is same as old one
if(strcmp($request->get('old_password'), $request->get('new_password')) == 0){
//Current password and new password are same
//return redirect()->back()->with("error","New Password cannot be same as your current password. Please choose a different password.");
return response()->json(['errors' => ['current'=> ['New Password cannot be same as your current password']]], 422);
}
$validatedData = $request->validate([
'old_password' => 'required',
'new_password' => 'required|string|min:6|confirmed',
]);
//Change Password
$user = Auth::user();
$user->password = Hash::make($request->get('new_password'));
$user->save();
return $user;
}
Laravel 5.8
Include this function in a controller:
public function updatePassword(Request $request)
{
$request->validate([
'password' => 'required',
'new_password' => 'required|string|confirmed|min:6|different:password'
]);
if (Hash::check($request->password, Auth::user()->password) == false)
{
return response(['message' => 'Unauthorized'], 401);
}
$user = Auth::user();
$user->password = Hash::make($request->new_password);
$user->save();
return response([
'message' => 'Your password has been updated successfully.'
]);
}
Don't forget to send new_password_confirmation as a parameter too, because when we use the validation rule confirmed for new_password for example, Laravel automatically looks for a parameter called new_password_confirmation in order to compare both fields.
You are validating request fields old_password, new_password and password_confirm here:
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
however your are using request fields current and password to verify current password and set a new one:
if (!Hash::check($request->current, $user->password)) {
// ...
$user->password = Hash::make($request->password);
Validated fields and used fields should be the same.
Here is my content.blade.php
<form action="{{ route('home') }}" method="post">
<input class="input-text" type="text" name="name" value="Your Name *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<input class="input-text" type="text" name="email" value="Your E-mail *" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">
<textarea name="text" class="input-text text-area" cols="0" rows="0" onFocus="if(this.value==this.defaultValue)this.value='';" onBlur="if(this.value=='')this.value=this.defaultValue;">Your Message *</textarea>
<input class="input-btn" type="submit" value="send message">
{{ csrf_field() }}
</form>
That's my routes(web.php)
Route::group(['middleware'=>'web'], function(){
Route::match(['get', 'post'], '/', ['uses'=>'IndexController#execute', 'as'=>'home']);
Route::get('/page/{alias}', ['uses'=>'PageController#execute', 'as'=>'page']);
Route::auth();
});
And Finally here is my IndexController.php, method execute():
if($request->isMethod('post')){
$messages = [
'required' => "Поле :attribute обязательно к заполнению",
'email' => "Поле :attribute должно соответствовать email адресу"
];
$this->validate($request, [
'name' => 'required|max:255',
'email' => 'required|email',
'text' => 'required'
], $messages);
dump($request);
}
So, the problem is that dump($request) does not work, and I also tried to comment everything except dump($request), and the result is the same. I think it just skips if($request->isMethod('post')) so that it returns that the method is not true, may be there is something wrong with token, I am not sure.
How to resolve this issue?
edit:
That's the code above if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Page;
use App\Service;
use App\Portfolio;
use App\People;
use DB;
class IndexController extends Controller
{
//
public function execute(Request $request){
You should assign $request to somewhere first.
For example, if i have a store method and i have to use Request $request for grabbing the information, i should establish it first, so by establishing it my application will recognize what does the variable is retrieving, let me show you an example code:
public function store(Request $request)
{
$data = $request->all();
$data['a'] = Input::get('a');
$data['b'] = Input::get('b');
$data['c'] = Input::get('c');
$data['d'] = Input::get('d');
$data['e'] = Input::get('e');
Letters::create($data);
return redirect::to('/');
}
Did you get it?
If not, here is an example with isMethod:
$method = $request->method();
if ($request->isMethod('post')) {
//
}
In your code i did not see the $var = $request->method(); (or what you want it to be).
I have a form which i am hoping to use to insert some data to mysql. I have setup the validator like this
public function insert_post(){
$rules = array(
'model' => 'required',
'country' => 'required',
'engine' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
echo '<pre>';
print_r($messages);
echo '</pre>';
return Redirect::to('create-posts')
->withErrors($validator);
}
else {
$i = new Text;
$i->model = request('model');
$i->country = request('country');
$i->engine = request('engine');
$i->save();
return redirect('/');
}
}
My create-posts route looks like this.
public function create_post(){
return view('create-posts');
}
However, its not displaying the error since i think i am loading a fresh create-posts and the validator messages are lost.
view code
<div class="form-group">
<label for="inputEmail" class="control-label col-xs-2">Model</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="inputEmail" name="model" placeholder="Model">
#if ($errors->has('model')) <p class="help-block">{{ $errors->first('model') }}</p> #endif
</div>
</div>
Is that what's the cause?.
In case you want to return to the last view, you can use:
return Redirect::back()->withErrors($validator);
Instead of return Redirect::to('create-posts')->withErrors($validator);.