How to keep session after storing data in Laravel 8? - php

I'm new to Laravel. I have created custom Change Password in Laravel 8 using Livewire. But, after succeeded in updating the user password, my session is expired and redirected to login page. So, the question is how to keep the session alive and redirect to the current page?
Here's my code:
ChangeUserPassword.php
class ChangeUserPassword extends Component
{
public $oldPassword;
public $newPassword;
public $confirmPassword;
public function render()
{
return view('livewire.auth.change-user-password');
}
public function changePassword()
{
$this->validate([
'oldPassword' => 'required',
'newPassword' => ['required', Password::min(8)
->letters()
->mixedCase()
->numbers()
->symbols()
// ->uncompromised()
],
'confirmPassword' => 'required|min:8|same:newPassword'
]);
$user = User::find(auth()->user()->id);
if (Hash::check($this->oldPassword, $user->password)) {
$user->update([
'password' => Hash::make($this->newPassword),
'updated_at' => Carbon::now()->toDateTimeString()
]);
$this->emit('showAlert', [
'msg' => 'Your password has been successfully changed.'
]);
return redirect()->route('user.changepassword');
} else {
$this->emit('showAlertError', [
'msg' => 'Old password does not match.'
]);
}
}
}
change-user-password.blade.php
<div class="col-md-12">
<div class="card">
<div class="card-body">
<h4 class="card-title ml-2">Change Password</h4>
<form wire:submit.prevent="changePassword" role="form">
#csrf
<div class="row">
<div class="form-group col-md-4">
<label for="oldPassword" class="form-label">Old Password<span style="color: red"> *</span></label>
<input class="form-control #error('oldPassword') is-invalid #enderror" wire:model="oldPassword" name="oldPassword" id="oldPassword" type="password" />
#error('oldPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group col-md-4">
<label for="newPassword" class="form-label">New Password<span style="color: red"> *</span></label>
<input class="form-control #error('newPassword') is-invalid #enderror" wire:model="newPassword" name="newPassword" id="newPassword" type="password" />
#error('newPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group col-md-4">
<label for="confirmPassword" class="form-label">Confirm Password<span style="color: red"> *</span></label>
<input class="form-control #error('confirmPassword') is-invalid #enderror" wire:model="confirmPassword" name="confirmPassword" id="confirmPassword" type="password" />
#error('confirmPassword')
<small id="helpId" class="text-danger">{{ $message }}</small>
#enderror
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary pull-right"
wire:loading.attr="disabled">Save</button>
{{-- <div wire:loading>
<img style="width: 25px;" src="{{ asset('assets/images/spinner-small.gif') }}" alt="Loading">
</div> --}}
</div>
</div>
</form>
</div>
</div>
</div>
<script>
document.addEventListener('livewire:load', function (e) {
e.preventDefault()
})
</script>
Any suggestion would really help. Thanks.

Authenticate the user again after updating the password
if (Hash::check($this->oldPassword, $user->password)) {
$user->update([
'password' => Hash::make($this->newPassword),
'updated_at' => Carbon::now()->toDateTimeString()
]);
$this->emit('showAlert', [
'msg' => 'Your password has been successfully changed.'
]);
if(Auth::attempt(['email'=>$user->email, 'password'=>$this->newPassword])){
$request->session()->regenerate();
return redirect()->intended('user.changepassword');
}
} else {
$this->emit('showAlertError', [
'msg' => 'Old password does not match.'
]);
}

Related

Laravel update only refreshes a page

My update page isn't working, when I'm submitting a form it only refreshes a page and adds some stuff to my URL, for example: http://127.0.0.1:8000/admin/employees/102/edit?_method=PUT&_token=mj3lrHqoYm1wiLwWiNQ8OX0kNRjmW4QVRuLpgZxY&image_path=&name=Libbie+Ebert&phone_number=380324244497&email=brekke.lola%40example.org&position_id=7&payment=186799&head=Asia+Frami&recruitment_date=2022-01-10. I already cleared route cache and its still not working, and also tried to use dd function but it's not showing up. What can be wrong? My model:
class Employee extends Model
{
use HasFactory;
protected $casts = [
'recruitment_date' => 'datetime:d-m-y',
];
protected $fillable= ['name', 'position_id', 'phone_number',
'recruitment_date', 'email', 'head',
'image_path', 'payment', 'admin_created_id', 'admin_updated_id'];
public function position()
{
return $this->belongsTo(Position::class, 'position_id');
}
}
Controller function:
public function update(StoreEmployeeRequest $request, $id){
$input = $request->validated();
$employee = Employee::findOrFail($id);
$employee->update([
'name' => $request->input('name'),
'position_id' => $request->input('position_id'),
'phone_number' => '+' . $request->input('phone_number'),
'recruitment_date' => $request->input('recruitment_date'),
'email' => $request->input('email'),
'head' => $request->input('head'),
'image_path' => $input['image_path'],
'payment' => number_format($request->input('payment')),
'admin_updated_id' => auth()->id(),
]);
return to_route('admin.employees.index');
}
Request:
public function rules()
{
return [
'name' => 'required|min:2|max:255',
'recruitment_date' => 'required|date',
'phone_number' => 'required',
'email' => 'required|email',
'payment' => 'required|numeric',
'position_id' => 'required',
'image_path' => 'image|mimes:jpg,png|max:5000|dimensions:min_width=300,min_height=300'
];
}
View:
<form action="{{ route('admin.employees.update', ['id' => $employee->id]) }}" enctype="multipart/form-data">
#method('PUT')
#csrf
<label for="image_path" class="form-label">Photo</label>
<input type="file" name="image_path" class="form-control-file" >
#error('image_path')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="name" class="form-label">Name</label>
<input type="text" name="name" class="form-control" value="{{ $employee->name }}" placeholder="Name is...">
#error('name')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="phone_number" class="form-label">Phone</label>
<input type="text" name="phone_number" class="form-control" value="{{ old('phone_number', preg_replace('/[^0-9]/', '', $employee->phone_number)) }}" placeholder="380...">
#error('phone_number')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="email" class="form-label">Email</label>
<input type="email" name="email" class="form-control" value="{{ old('email', $employee->email) }}" placeholder="Email is...">
#error('email')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="position_id" class="form-label">Position</label>
<select class="form-control" name="position_id" aria-label=".form-select-lg example">
#foreach ($positions as $position)
<option value="{{ $position->id }}" {{$employee->position_id == $position->id ? 'selected' : ''}}>{{ $position->name }}</option>
#endforeach
</select>
#error('position_id')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="payment" class="form-label">Salary, $</label>
<input type="text" name="payment" class="form-control" value="{{ old('payment', preg_replace('/[^0-9]/', '', $employee->payment)) }}" placeholder="Salary is...">
#error('payment')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="head" class="form-label">Head</label>
<input type="text" id="head" name="head" class="form-control" value="{{ old('head', $employee->head) }}" placeholder="Head is...">
#error('head')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<label for="recruitment_date" class="form-label">Date</label>
<input type="datetime-local" name="recruitment_date" value="{{ old('recruitment_date', $employee->recruitment_date) }}" class="form-control">
#error('recruitment_date')
<div class="alert alert-danger mt-2" role="alert"><strong>{{ $message }}</strong></div>
#enderror
<div class="mt-4 text-center">
<button type="submit" class="btn btn-secondary">Submit</button>
</div>
</form>
Route:
Route::put('/admin/employees/{id}/edit', [EmployeeController::class, 'update'])->name('admin.employees.update');
You are missing the method attribute in your form, and the default one is GET. Adding #method('PUT') is not enough.
Change your code like this:
<form
action="{{ route('admin.employees.update', ['id' => $employee->id]) }}"
method="POST"
enctype="multipart/form-data">
i think you should you POST method while submitting the form.

login and registration page not jump to the dashboard after registration and login process

I'm new to Laravel, and I'm trying to create a Login and Registration page using this reference Link
I have done the same code, but after login, it does not jump to the Dashboard page, even after Registration also pages do not jump to the Dashboard, now I'm too confused why it's not working, what I have to do the wrong thing here.
please help me with this.
My code
Web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\CustomAuthController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/*Route::get('', function () {
return view('auth/login');
});*/
Route::get('dashboard', [CustomAuthController::class, 'dashboard']);
Route::get('login', [CustomAuthController::class, 'index'])->name('login');
Route::post('custom-login', [CustomAuthController::class, 'customLogin'])->name('login.custom');
Route::get('registration', [CustomAuthController::class, 'registration'])->name('register-user');
Route::post('custom-registration', [CustomAuthController::class, 'customRegistration'])->name('register.custom');
Route::get('signout', [CustomAuthController::class, 'signOut'])->name('signout');
Path : E:\xampp\htdocs\xyz\app\Http\Controllers
CustomAuthController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Hash;
use Session;
use Redirect;
use App\Models\User;
use App\Models\Admin;
class CustomAuthController extends Controller
{
public function index()
{
return view('auth.login');
}
public function registration()
{
return view('auth.registration');
}
public function customLogin(Request $request)
{
//dd('login');
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
//return redirect()->intended('dashboard')->withSuccess('Signed in');
return redirect("dashboard")->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
public function customRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
Auth::login($user);
return redirect("dashboard")->withSuccess('You have signed-in');
}
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('You are not allowed to access');
}
public function create(array $data)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
public function signOut() {
Session::flush();
Auth::logout();
return Redirect('login');
}
}
in this CustomAuthController there is a function customLogin and customRegistration
if condition is not work I think so.
Path : E:\xampp\htdocs\xyz\resources\views\auth
registration.blade.php
**
#include('header')
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper">
<div class="content-wrapper d-flex align-items-center auth px-0">
<div class="row w-100 mx-0">
<div class="col-lg-4 mx-auto">
<div class="auth-form-light text-left py-5 px-4 px-sm-5">
<div class="brand-logo">
<!-- <img src="../../images/logo.svg" alt="logo"> -->
<img src = "{{ asset('/images/logo2.png') }}" alt="logo"/>
</div>
<h4>New here?</h4>
<h6 class="font-weight-light">Signing up is easy. It only takes a few steps</h6>
<form class="pt-3" action="{{ route('register.custom') }}" method="POST">
#csrf
<div class="form-group">
<input type="text" class="form-control form-control-lg" id="name" name="name" placeholder="Username">
#if ($errors->has('name'))
<span class="text-danger">{{ $errors->first('name') }}</span>
#endif
</div>
<div class="form-group">
<input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email">
#if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Password">
#if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="mb-4">
<div class="form-check">
<label class="form-check-label text-muted">
<input type="checkbox" class="form-check-input">
I agree to all Terms & Conditions
</label>
</div>
</div>
<div class="mt-3">
<!-- <a class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn" >SIGN UP</a> -->
<button type="submit" class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn">SIGN UP</button>
</div>
<div class="text-center mt-4 font-weight-light">
Already have an account? Login
</div>
</form>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
#include('footer')**
Path : E:\xampp\htdocs\xyz\resources\views\auth
login.blade.php
#include('header')
#extends('layouts.layout')
#section('content')
<div class="container-scroller">
<div class="container-fluid page-body-wrapper full-page-wrapper">
<div class="content-wrapper d-flex align-items-center auth px-0">
<div class="row w-100 mx-0">
<div class="col-lg-4 mx-auto">
<div class="auth-form-light text-left py-5 px-4 px-sm-5">
<div class="brand-logo">
<!-- <img src="../../images/logo.svg" alt="logo"> -->
<img src = "{{ asset('/images/logo2.png') }}" />
</div>
<h4>Hello! let's get started</h4>
<h6 class="font-weight-light">Sign in to continue.</h6>
#if (Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
<form class="pt-3" action="{{ route('login.custom') }}" method="POST">
#csrf
<div class="form-group">
<input type="email" class="form-control form-control-lg" name="email" id="email" placeholder="Username">
#if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" id="password" placeholder="Password">
#if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="mt-3">
<!-- <a class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn"
href="{{ url('login.custom') }}">SIGN IN</a> -->
<button type="submit" class="btn btn-block btn-primary btn-lg font-weight-medium auth-form-btn">SIGN IN</button>
</div>
<div class="my-2 d-flex justify-content-between align-items-center">
<!-- <div class="form-check">
<label class="form-check-label text-muted">
<input type="checkbox" class="form-check-input">
Keep me signed in
</label>
</div> -->
Forgot password?
</div>
<!-- <div class="mb-2">
<button type="button" class="btn btn-block btn-facebook auth-form-btn">
<i class="ti-facebook mr-2"></i>Connect using facebook
</button>
</div> -->
<div class="text-center mt-4 font-weight-light">
Don't have an account? Create
</div>
</form>
</div>
</div>
</div>
</div>
<!-- content-wrapper ends -->
</div>
<!-- page-body-wrapper ends -->
</div>
#include('footer')
#endsection
Path : E:\xampp\htdocs\xyz\resources\views\dashboard.php
dashboard.php
In the registration, you're just creating the user, you're not logging the user in. Use Auth::login($user); to login the user.
In the login, you're using redirect()->intended, i think its intending to go to the login page instead of dashboard read THIS or THIS to read more about redirect()->intended.
public function customRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$user = $this->create($data);
Auth::login($user);
return redirect("dashboard")->withSuccess('You have signed-in');
}
public function customLogin(Request $request)
{
//dd('login');
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect("dashboard")->withSuccess('Signed in');
}
return redirect("login")->withSuccess('Login details are not valid');
}
i think its just a syntax error. you have to implement a middle-ware for
protecting the routes from users to access without login
your custom login method should be like this
public function authenticate(LoginRequest $request)
{
if(Auth::attempt([
'phonenumber'=>$request->phonenumber,
'password'=>$request->password],
$remember=$request->has('remember')?true:false))
{
return redirect()->route('dashboard');
}
}
i hope it helps you if you having a doubt..
Look after this github open repo

How do I keep the value of a checkbox in an invalid form in this Laravel 8 application?

I am working on a Laravel 8 blogging application. The "Add article" form has a "switch" (checkbox) that lets the user choose whether or not the post will be a featured one.
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}" enctype="multipart/form-data" novalidate>
#csrf
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input id="featured" class="mt-1" type="checkbox" name="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<button type="submit" class="w-100 btn btn-primary">{{ __('Save') }}</button>
</form>
The controller:
class ArticleController extends Controller
{
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:190',
'short_description' => 'required|string|max:190',
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'short_description.max' => 'The short description field is too long',
];
public function categories() {
return ArticleCategory::all();
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Turn the 'featured' field value into a tiny integer
$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'featured' => $fields['featured'],
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'The article titled "' . $form_data['title'] . '" was added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The problem
When an attempt is made to submit the invalid form, the fields that are valid keep their values.
The unintended exception to the rule is the checkbox <input id="featured" class="mt-1" type="checkbox" name="featured">
What is my mistake?
Your input has no value, so you can only check on existence not on value in controller ($request->get('featured') will never have the value on)
You need to use old('featured') on that field too
You can skip the check on the featured field in the controller if you set the values to 0 and 1 in the form
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input type="hidden" value="0" name="featured">
<input {{ old('featured') ? 'checked':'' }} id="featured" value="1" class="mt-1" type="checkbox" name="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
The hidden field is to send the value 0 if the checkbox is not checked. A checkbox input is not sent in the request if it is not checked.
When checked, the input value will be overwritten to 1.
In the controller you can directly use the input
$fields = $validator->validated();
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'featured' => $fields['featured'],
];

Why create function in RegisterController is not working in laravel

I am new to Laravel. I am using registerController in Laravel to create users . Users data are stored in Users table.
What I have tried is :
#extends('adminlte::auth.auth-page', ['auth_type' => 'register'])
#php( $login_url = View::getSection('login_url') ?? config('adminlte.login_url', 'login') )
#php( $register_url = View::getSection('register_url') ?? config('adminlte.register_url', 'register') )
#if (config('adminlte.use_route_url', false))
#php( $login_url = $login_url ? route($login_url) : '' )
#php( $register_url = $register_url ? route($register_url) : '' )
#else
#php( $login_url = $login_url ? url($login_url) : '' )
#php( $register_url = $register_url ? url($register_url) : '' )
#endif
#section('auth_header', __('adminlte::adminlte.register_message'))
#section('auth_body')<!-- comment -->
<?php $roles = DB::table('roles')->where('id','>',1)->get(); ?>
<div class="login-form">
<div class="container">
<div class="row ">
<div class="register-box">
<div class="register-box-header">
<p class="login-box-msg">{{!empty($type) && $type == 'Agronamist' ? 'Buyer' : ''}} REGISTRATION FORM</p>
</div>
<div class="register-box-body register_body">
<form method="POST" action="{{ route('register') }}" class="registerForm" enctype="multipart/form-data">
#csrf
#if(empty($type))
<div class="row">
<div class="col-md-12 text-center">
<div class="form-group has-feedback">
<select name="role" class="form-control" onchange='window.location.href=window.location.origin+"/register?role="+$(this).val();' required>
<option value="">Select a Role</option>
#foreach($roles as $role)
<option value="{{$role->id}}" {{(count($_GET)>0 && $_GET['role'] == $role->id) ? 'selected' : ''}}>{{$role->name}} </option>
#endforeach
</select>
</div>
</div>
</div>
#else
<input type="hidden" name="role" value="2">
<input type="hidden" name="type" value="{{$type}}">
#endif
#if(count($_GET)>0 && $_GET['role'] != '')
<?php $states = DB::table('states')->orderBy('name','asc')->get();?>
<div class="row">
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="First Name *" name="first_name" value="{{ old('first_name') }}" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Last Name *" name="last_name" value="{{ old('last_name') }}" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="email" class="form-control" name="email" value="{{ old('email') }}" placeholder="Email *" required>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control phoneMask" placeholder="Phone *" name="phone" value="{{ old('phone') }}" required>
<span class="glyphicon glyphicon-phone form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Address *" name="address" value="{{ old('address') }}" required>
<span class="glyphicon glyphicon-map-marker form-control-feedback"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="password" class="form-control #error('password') is-invalid #enderror" name="password" placeholder="Password *" required autocomplete="new-password">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="form-group has-feedback">
<input type="password" class="form-control" name="password_confirmation" placeholder="Retype password *" required autocomplete="new-password">
<span class="glyphicon glyphicon-log-in form-control-feedback"></span>
</div>
</div>
<div class="row">
<div class="col-md-3 col-xs-offset-4 submit_btn">
<button type="submit" class="btn btn-primary btn-block btn-flat">Register</button>
</div>
</div>
#endif
</form>
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\manager_group;
use App\User;
use App\UserAddresses;
use App\UserDetails;
use App\UserRoles;
use Auth;
use DB;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
//$this->middleware('guest');
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
// dd($this->validator($request->all())->validate());
event(new Registered($user = $this->create($request->all())));
if (array_key_exists('type', $request->all())) {
return $this->registered($request, $user) ?: redirect('/buyersList/' . Auth::user()->id)->with('success', 'Registered successfully.');
} else {
return $this->registered($request, $user) ?: redirect($this->redirectPath())->with('success', 'Registered successfully. Please wait for the approval to access your account.');
}
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'phone' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
My data is not inserting to users table,and the create function is not working when I dd($user) it. How to make my code working. What my page shows when I try to submit data is :
Here is some really good baseline code that can be used if you simply want to store user input.
For example -
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
*
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
}
If you want to keep your validation out of your controller you can create a request to handle your validation.
Make a UserStoreRequest.php using Artisan command make:request. From there you can validate the request from the user to ensure they have all of the data you want.
Laravel has some good documentation on this as well. https://laravel.com/docs/8.x/validation

My table is updating but not validated before update in Laravel 6

I'm using Laravel for the first time, version 6.2. My code is working well for updating the table on the DB but it does not validate the data before update. This is the first time I need to validate my form on my own (not the default laravel auth) and I think I'm missing something basic to get it to work.
I'm trying to make the typical change password form with current-password - new password - confirm the new password. Below is my route, my controller and my view.
Routes
Route::get('/cambiarclave', 'Auth\ChangePasswordController#showChangeForm');
Route::post('/cambiarclave', 'Auth\ChangePasswordController#changePassword')->name('cambiarclave');
ChangePasswordController.php
class ChangePasswordController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function showChangeForm()
{
return view('auth.cambiarclave');
}
protected function validator(array $data)
{
return Validator::make($data, [
'clave-actual' => ['required', 'string', 'min:6'],
'nueva-clave' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
public function changePassword(request $request)
{
$data = $request->all();
$user = User::find(auth()->user()->id);
if (!Hash::check($data['clave-actual'], $user->password)) {
return back()->with('error', 'You have entered wrong password');
}
$user_id = $user;
$obj_user = User::find($user_id);
$obj_user->password = \Hash::make($request->input('nueva-clave'));
$obj_user->save();
auth()->logout();
return redirect('/ingreso');
}
}
cambiarclave.blade.php
<form method="POST" id="change-password" role="form" name="change-password" action="{{ route('cambiarclave') }}"
novalidate>
#csrf
<div class="form-group row">
<label for="clave-actual" class="col-md-6 col-form-label text-md-right">{{ __('Clave actual') }}</label>
<div class="col-md-5">
<input type="password" class="form-control" id="clave-actual" name="clave-actual" placeholder="Password"
required autofocus>
#if ($errors->has('clave-actual'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('clave-actual') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="nueva-clave" class="col-md-6 col-form-label text-md-right">{{ __('Nueva clave') }}</label>
<div class="col-md-5">
<input type="password" class="form-control" id="nueva-clave" name="nueva-clave" placeholder="Password"
required autofocus>
#if ($errors->has('nueva-clave'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('nueva-clave') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="nueva-clave-confirm"
class="col-md-6 col-form-label text-md-right">{{ __('Confirmar nueva clave') }}</label>
<div class="col-md-5">
<input type="password" class="form-control" id="nueva-clave-confirm" name="nueva-clave-confirm"
placeholder="Password" required autofocus>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-4">
<button type="submit" class="btn btn-primary w-50">
<p class="h5 p-0 mt-1">{{ __('Cambiar') }}</p>
</button>
</div>
</div>
</form>
You miss here executing your validator method. You should add code like this:
$validator = $this->validator($data);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
after
$user = User::find(auth()->user()->id);
line in your controller to run validation.

Categories