Hey I'm trying to do a reset password validation and the user must insert the current password to validate, but I'm getting a error "Possible typo $users Did you mean $errors?" it says that $users is undefined.
This is my view:
#if (Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
<div class="container">
#foreach($users as $user)
#if($user->id == Auth::id())
<h1> Bem-Vindo, <span> {{ $user->name }} </span>!</h1>
#endif
#endforeach
<ul>
<li> <a href="#"> <img src="img/perfil/profile_icon.png" alt="user profile" width="38"
height="35"> DETALHES DA CONTA</a> </li>
<li> <a class="" href="#"> <img src="img/perfil/order_icon.png" alt="user profile" width="38" height="35">
ENCOMENDAS</a> </li>
<li> <a class="" href="#"> <img src="img/perfil/logout_icon.png" alt="user profile" width="38" height="35">
LOGOUT</a> </li>
</ul>
<form method="post" action="{{ route('perfil.update' )}}" >
#csrf
#foreach($users as $user)
#if($user->id == Auth::id())
<div id="primeiro_nome">
<label for="fname">PRIMEIRO NOME:</label><br>
<input disabled type="text" id="fname" name="name" value="{{ $user->name }}" ><br>
</div>
<div id="ultimo_nome">
<label for="lname">ÚLTIMO NOME:</label><br>
<input disabled type="text" id="lname" name="surname" value="{{ $user->surname }}">
</div>
<div id="email1">
<br><label for="lname">EMAIL:</label><br>
</div>
<div id="email2">
<input disabled type="email" id="email" name="email" value="{{ $user->email }}">
</div>
#endif
#endforeach
<button type="button" class="submitbtn" id="alterar"> ALTERAR DADOS</button>
<button class="submitbtn" id="submeter" type="submit" " > SUBMETER </button>
</form>
<div class="panel-body">
#if (session('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
#endif
#if($errors)
#foreach ($errors->all() as $error)
<div class="alert alert-danger">{{ $error }}</div>
#endforeach
#endif
<form class="form-horizontal" method="POST" action="{{ route('changePasswordPost') }}">
{{ csrf_field() }}
<h3> ALTERAR PASSWORD </h3>
<div class="form-group{{ $errors->has('current-password') ? ' has-error' : '' }}">
<label for="new-password" class="col-md-4 control-label">Current Password</label>
<div class="col-md-6">
<input id="current-password" type="password" class="form-control" name="current-password" required>
#if ($errors->has('current-password'))
<span class="help-block">
<strong>{{ $errors->first('current-password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('new-password') ? ' has-error' : '' }}">
<label for="new-password" class="col-md-4 control-label">New Password</label>
<div class="col-md-6">
<input id="new-password" type="password" class="form-control" name="new-password" required>
#if ($errors->has('new-password'))
<span class="help-block">
<strong>{{ $errors->first('new-password') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="new-password-confirm" class="col-md-4 control-label">Confirm New Password</label>
<div class="col-md-6">
<input id="new-password-confirm" type="password" class="form-control" name="new-password_confirmation" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Change Password
</button>
</div>
</div>
This is my controller called PerfilController:
public function showChangePasswordGet() {
return view('perfil');
}
public function changePasswordPost(Request $request) {
$users = User::all();
return view('perfil', compact('users'));
if (!(Hash::check($request->get('current-password'), Auth::id()->password))) {
// The passwords matches
}
if(strcmp($request->get('current-password'), $request->get('new-password')) == 0){
// Current password and new password same
}
$validatedData = $request->validate([
'current-password' => 'required',
'new-password' => 'required|string|min:8|confirmed',
]);
//Change Password
$user = Auth::id();
$user->password = bcrypt($request->get('new-password'));
$user->save();
return redirect()->back()->with("success","Password successfully changed!");
}
And this is my routes:
Route::get('/perfil', [PerfilController::class, 'showChangePasswordGet'])->name('changePasswordGet');
Route::post('/perfil', [PerfilController::class, 'changePasswordPost'])->name('changePasswordPost');
What I'm doing wrong? Thanks in advance.
You have some logical error in your code. I have added corrected code below.
public function showChangePasswordGet() {
$users = User::all();
return view('perfil', compact('users'));
}
public function changePasswordPost(Request $request) {
if (Hash::check($request->get('current-password') != Auth::user()->password))) {
return redirect()->back()->withError('Incorrect current-password');
}
if($request->get('current-password') == $request->get('new-password')){
return redirect()->back()->withError('New Password should not be same as current-password');
}
$validatedData = $request->validate([
'current-password' => 'required',
'new-password' => 'required|string|min:8|confirmed',
]);
//Change Password
$user = Auth::user();
$user->password = bcrypt($request->get('new-password'));
$user->save();
return redirect()->back()->with("success","Password successfully changed!");
}
Related
In my laravel project am using js validator, but during form updation , Validation is not working. My form is not submitting, if I did not made any changes. Sometimes it shows error to the email field.
Following is my validation code,
protected $edituserValidationRules = [
'user_name' => 'required',
'email' => 'required|email|max:255|unique:users',
];
Following is the code to pass validation and other things to view
public function viewUsers($id)
{
$users = User::find($id);
$validator = JsValidator::make($this->edituserValidationRules,[],[],'#useredit');
return view('user.update')->with(['validator' => $validator,'users'=> $users]);
}
Following is the code to update that particular user
public function updateUsers(Request $request , $id)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:users' . $request->id
]);
$postdata = $request->all();
$user = new User;
$user = User::find($id);
$hashedRandomPassword = Hash::make($postdata['password'], [
'rounds' => 12
]);
$api_key = Str::random(16);
$checkApiKey = User::where('api_key', $api_key)->first();
if(!empty($checkApiKey)) {
$api_key = Str::random(16);
}
$user = new User;
$user->name=$postdata['user_name'];
$user->email=$postdata['email'];
$user->password= $hashedRandomPassword;
$user->ip_address=$request->ip();
$user->api_key=$api_key;
if($user->save()){
Session::flash('message', 'User Updated Sucessfully');
Session::flash('msgclass', 'alert-success');
}
return redirect('users');
}
Following is the code in view page
#extends('user.layout.app')
#section('content')
<script src="{{ url('js/user/location.js') }}"></script>
<div class="container-fluid add-location">
<div class="row">
<div class="col-md-12">
<div class="card">
<form method="post" action="{!! route('updateUsers', [$users->id]); !!}" name="useredit" id="useredit" enctype="multipart/form-data" novalidate>
{{ csrf_field() }}
<div class="card-header">
<h4 class="card-title"> Edit User </h4>
</div>
#if(!empty($errors->all()))
<div class="row"> #foreach ($errors->all() as $error)
<div class="col-lg-12">
<div class="alert alert-danger"> <span>{{ $error }}</span> </div>
</div>
#endforeach </div>
#endif
<div class="card-content">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label class="control-label">Full Name
<star>*</star>
</label>
<input id="user_name" name="user_name" class="controls form-control" type="text" placeholder="User Name" value="{{$users->name}}">
#if ($errors->has('user_name')) <span class="help-block"> {{ $errors->first('user_name') }} </span> #endif </div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="control-label">Email
<star>*</star>
</label>
<input id="email" type="email" class="form-control" name="email" value="{{$users->email}}" placeholder="Email">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<!-- <div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="control-label">Password
<star>*</star>
</label>
<input id="password" type="password" class="form-control" name="password" value="{{bcrypt($users->password)}}">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
</div> -->
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6">
<div class="col-xs-12 col-sm-12 col-md-12 form-action">
<button type="submit" class="btn btn-fill btn-info">Submit</button>
Cancel </div>
</div>
</form>
</div>
</div>
</div>
</div>
{!! $validator !!}
#endsection
What is the problem here, during adding customers, I am checking for email already exists, same is checking here also.
I don't know what is happening? Please help
try changing this line
$this->validate($request, [
'email' => 'required|email|max:255|unique:users' . $request->id
]);
to
$request->validate([
'email' => 'required|email|max:255|unique:users,email,'.$id
]);
Adding ',id' end of the statement which is used to prevent email exist check for the current id...
$request->validate([
'email' => 'required|email|max:255|unique:users,email,'.$request->id.',id',
]);
I am having trouble when inputting data and figuring out why my data is not being stored into the database. I have tried to use the resources route and my custom route code, but it seems still nothing works. Clicking submit just seems to refresh the page with no errors to show
And here is my form :
<div class="container">
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-expand-sm navbar-dark primary justify-content-between">
<div class="navbar-brand text-dark">Create a Story</div>
</nav>
<hr class="mt-3">
<form action="{{route('story.store')}}" method="post">
#csrf
<div class="row">
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="title">Title</label><br>
<input type="text" name="title" id="title" class="w-100 form-control{{ $errors->has('title') ? ' is-invalid' : '' }}" value="{{ old('title') }}" required>
#if ($errors->has('title'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('title') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="category">Category</label><br>
<select name="category" id="category" class="w-100 form-control{{ $errors->has('category') ? ' is-invalid' : '' }}" value="{{ old('category') }}" required>
<option value="Active" selected>Select Category</option>
#foreach ($category as $item)
<option value="{{$item->id}}">{{$item->nama}}</option>
#endforeach
</select>
#if ($errors->has('category'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('category') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-6">
<div class="form-group my-3">
<label for="thumbnail">Story Thumbnail <span class="text-muted">(Recomended size is 650 x 350 pixel)</span></label><br>
<input type="file" name="thumbnail" id="thumbnail">
#if ($errors->has('thumbnail'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('thumbnail') }}</strong></span>
#endif
</div>
</div>
<div class="col col-lg-12">
<div class="form-group mt-4">
<textarea id="text-content" name="content" class="w-100 form-control{{$errors->has('content') ? ' is-invalid' : ''}}" id="content" rows="3" value="{{old('content')}}"></textarea>
#if ($errors->has('content'))
<span class="invalid-feedback" role="alert"><strong>{{ $errors->first('content') }}</strong></span>
#endif
</div>
</div>
</div>
<div class="modal-footer pb-0">
<div class="float-right">
<button type="submit" class="btn btn-outline-primary btn-md">Publish Story</button>
</div>
</div>
</form>
</div>
</div>
The store function in controller :
public function store(Request $request)
{
$user = Auth::user();
$request->validate([
'title' => 'required|string',
'category' => 'required',
'thumbnail' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'content' => 'required',
]);
$thumbnailName = time().'.'.request()->thumbnail->getClientOriginalExtension();
$post = new Post;
$post->title = request('title');
$post->category_id = request('category');
$post->thumbnail = request('thumbnail');
$post->content = request('content');
$post->title = request('title');
$post->date = date('d-m-Y');
$post->author_id = $user->id;
$post->save();
$request->thumbnail->move(asset('storage/uploads'), $thumbnailName);
return redirect('me/stories')->with('Succes', 'Story has been published')->with('thumbnail', $thumbnailName);
}
And this is the routes:
Route::get('me/stories', 'PostController#index')->name('story');
Route::get('me/stories/create', 'PostController#create')->name('story.create');
Route::post('me/stories/store', 'PostController#store')->name('story.store');
Route::post('ck/image_upload', 'PostController#imageUpload')->name('ck.upload');
I'm not getting any error messages at all, it's just that the submission button does nothing. Thanks a lot!
Clicking submit just seems to refresh the page with no errors to show
Your Validator is doing a return to last page with the errors.
Add this snippet of code to your blade
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Also, inspect the page before submitting and go to the network tab (check preserve log at the top) and proceed with the submission, you will get more details of what happened.
I'm creating a file called edit.blade to edit users.
The problem is, when i'm trying to make a list with all roles, Laravel prints the following error:
Undefined variable: roles (View: /home/ubuntu/workspace/resources/views/user/edit.blade.php)
Here is my edit.blade template:
#extends ('adminlte::page')
#section('content')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<div class="container" style="margin-left:25%">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Editar datos del Usuario</h2>
</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" action="{{ route('user.update', ['user' => $user->id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT"/>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">
Nombre
</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" name="name" value="{{ $user->name }}" autofocus style=" ">
#if ($errors->has('name'))
<span class="help-block">
<strong style=" ">{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">
Email
</label>
<div class="col-md-6">
<input id="email" type="text" class="form-control" name="email" value="{{ $user->email }}" autofocus style=" ">
#if ($errors->has('email'))
<span class="help-block">
<strong style=" ">{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="club" class="col-md-4 control-label">
Club
</label>
<div class="col-md-6">
<select name="id_club" >
#foreach($clubs as $club)
<option value="{{$club->id_club}}" class="form-control">{{$club->nombre}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="roles" class="col-md-4 control-label">
Rol
</label>
<div class="col-md-6">
<select name="role_id" >
#foreach($roles as $role)
<option value="{{$role->id}}" class="form-control">{{$role->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
And my this is my UserController that calls the blade template with the relevant variables:
public function edit(User $user)
{
$roles = Role::all();
$clubs = Club::all();
return view('user.edit', ['user' => $user], ['clubs' => $clubs], ['roles' => $roles]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
$user->save();
$user->roles()->sync([$request->input('role_id')]);
//$user->update($request->all());
return redirect()->route('user.index');
}
I'm including use App\Role; at the top of this file.
Change this:
return view('user.edit', ['user' => $user], ['clubs' => $clubs], ['roles' => $roles]);
to this:
return view('user.edit', ['user' => $user, 'clubs' => $clubs, 'roles' => $roles]);
The view() accepts the data you want to send to the view as an array as a second param.
You can also use view(...)->with(compact('user', 'clubs', 'roles'))
I created a registration form using make:auth command in Laravel 5.5. Its working alright but not showing errors when validation fails. I've checked many times that code to display errors exists in template but still getting this error.
Template Location:
resources/views/mybladetemplate
Method in Controller:
protected function validator(array $data)
{
return Validator::make($data, [
'field1' => 'required|string|max:255',
'emailField' => 'required|string|email|max:255|unique:users',
'fieldPwd' => 'required|string|min:6|confirmed',
'anotherfield' => 'string'
]);
}
RegistersUsers Trait:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Registeration Form:
<form class="form-horizontal" method="POST" action="{{ route('register') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('field1') ? ' has-error' : '' }}">
<label for="name" class="col-md-4 control-label">Field Name</label>
<div class="col-md-6">
<input id="field1" type="text" class="form-control" name="field" value="{{ old('field1') }}" required autofocus>
#if ($errors->has('field1'))
<span class="help-block">
<strong>{{ $errors->first('field1') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('emailField') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input id="emailField" type="email" class="form-control" name="emailField" value="{{ old('emailField') }}" required>
#if ($errors->has('emailField'))
<span class="help-block">
<strong>{{ $errors->first('emailField') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="anotherfield" class="col-md-4 control-label">Another Field</label>
<div class="col-md-6">
<input id="anotherfield" type="text" class="form-control" name="anotherfield" value="{{ old('anotherfield') }}" />
</div>
</div>
<div class="form-group{{ $errors->has('fieldPwd') ? ' has-error' : '' }}">
<label for="fieldPwd" class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="fieldPwd" type="password" class="form-control" name="fieldPwd" required>
#if ($errors->has('fieldPwd'))
<span class="help-block">
<strong>{{ $errors->first('fieldPwd') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group">
<label for="password-confirm" class="col-md-4 control-label">Confirm Password</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">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Register
</button>
</div>
</div>
</form>
Use this simple code in your blade to show all of the errors in a ul li structure :
#if($errors->any())
#foreach ($errors->all() as $error)
<div class="alert alert-warning" dir="rtl">
<ul>
<li>{!! $error !!}</li>
</ul>
</div>
#endforeach
#endif
I'm following a tutorial about Authorization in laravel, but it seems it got some errors in the code like this:
"Type error: Argument 2 passed to App\Providers\AuthServiceProvider::App\Providers\{closure}() must be an instance of App\Providers\Post, instance of App\Post given, called in E:\xampp\htdocs\cms\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php on line 323 ◀"
I got those error code when I'm accessing http://cms.dev/posts/edit/2. here's the code that i've put on AuthServicesProfider:
public function registerPostPolicies()
{
Gate::define('create-post', function ($user) {
return $user->hasAccess(['create-post']);
});
Gate::define('update-post', function ($user, Post $post) {
return $user->hasAccess(['update-post']) or $user->id == $post->user_id;
});
Gate::define('publish-post', function ($user) {
return $user->hasAccess(['publish-post']);
});
Gate::define('see-all-drafts', function ($user) {
return $user->inRole('editor');
});
}
and here's the code for the update.blade:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Update Post</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('update_post', ['post' => $post->id]) }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
<label for="title" class="col-md-4 control-label">Title</label>
<div class="col-md-6">
<input id="title" type="text" class="form-control" name="title" value="{{ old('title', $post->title) }}" required autofocus>
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group{{ $errors->has('body') ? ' has-error' : '' }}">
<label for="body" class="col-md-4 control-label">Body</label>
<div class="col-md-6">
<textarea name="body" id="body" cols="30" rows="10" class="form-control" required>{{ old('body', $post->body) }}</textarea>
#if ($errors->has('body'))
<span class="help-block">
<strong>{{ $errors->first('body') }}</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">
Update
</button>
#can('publish-post')
<a href="{{ route('publish_post', ['post' => $post->id]) }}" class="btn btn-primary">
Publish
</a>
#endcan
<a href="{{ route('list_posts') }}" class="btn btn-primary">
Cancel
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
I really have no idea about how to fix it since i really don't understand about authorization in Laravel. Thanks.
You're missing a use statement for the Post class, therefore PHP assumes the gate takes the Post class from the current namespace, hence the App\Providers\Post in the error message.
Add the following in the provider class:
use App\Post;