I cannot set correctly validation in Laravel.
Among other functions I have this in the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\RimborsiExport;
use DB;
use App\Customers;
use App\Claims;
use App\Refunds;
use App\Services;
use App\Http\Requests\RefundsPost;
use Excel;
use DataTables;
use Redirect;
use Response;
class RefundsController extends Controller
{
public function storeRefundsData(RefundsPost $request){
dd($request);
//$validated = $request->validated();
$customers = Customers::create($request->all());
return back()->with('status', 'Dati Cliente inseriti correttamente');
}
}
I have also defined a custom Request type
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RefundsPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
return $rules;
}
public function messages()
{
return [
'contr_nom.required' => "Il Nome Contraente e' obbligatorio",
'contr_cog.required' => "Il Cognome Contraente e' obbligatorio",
'polizza.required' => "Il numero di polizza e' obbligatorio",
'email.required' => "Una mail e' obbligatoria per le comunicazioni",
'targa.required' => "La targa e' obbligatoria",
'data_sin.required' => "La data sinistro e' obbligatoria",
'iban.required' => "Il numero IBAN e' obbligatorio",
'int_iban.required' => "L'intestatario dell' IBAN e' obbligatorio",
'dossier.required' => "Il numero di dossier e' obbligatorio",
'cliente.required' => "Il cliente e' obbligatorio",
'stato.required' => "Lo stato del rimborso e' obbligatorio",
'date_ref.required' => "La data della richiesta e' obbligatoria",
];
}
}
and i have this blade with the form inside
<div class="container-fluid">
<form method="POST" action="{{ route('storeRefundsData') }}" novalidate>
{{ csrf_field() }}
<h5 class="mb-3">Anagrafica</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="contr_nom">Nome Contraente</label>
<input type="text" class="form-control #error('contr_nom') is-invalid #enderror" id="contr_nom" name="contr_nom" value="{{old('contr_nom')}}">
#error('contr_nom')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="contr_cog">Cognome Contraente</label>
<input type="text" class="form-control #error('contr_cog') is-invalid #enderror" id="contr_cog" name="contr_cog" value="{{old('contr_cog')}}">
#error('contr_cog')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="polizza">Numero Polizza <span class="text-muted"></span></label>
<input type="text" class="form-control #error('polizza') is-invalid #enderror" id="polizza" name="polizza" value="{{old('polizza')}}">
#error('polizza')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="email">Email <span class="text-muted"></span></label>
<input type="email" class="form-control #error('email') is-invalid #enderror" id="email" name="email" placeholder="tu#esempio.it" value="{{old('email')}}">
#error('email')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="targa">Targa veicolo</label>
<input type="text" class="form-control #error('targa') is-invalid #enderror" id="targa" name="targa" placeholder="Inserisci la targa" value="{{old('targa')}}">
#error('targa')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<h5 class="mb-3">Dati bancari</h5>
<div class="row">
<div class="col-md-6 mb-3">
<label for="iban">IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('iban') is-invalid #enderror" id="iban" name="iban" placeholder="Inserisci il tuo IBAN" value="{{old('iban')}}">
#error('iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
<div class="col-md-6 mb-3">
<label for="int_iban">Intestatario IBAN <span class="text-muted"></span></label>
<input type="text" class="form-control #error('int_iban') is-invalid #enderror" id="int_iban" name="int_iban" placeholder="Inserisci l'intestatario dell'IBAN" value="{{old('int_iban')}}">
#error('int_iban')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
</div>
</div>
<hr class="mb-4">
<!-- <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>-->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Salva">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
</form>
</div>
I cannot understand why when i click on form submit button to create a new row in the db, it seems that even it doesn't enter Controller function.
If I use Request instead of custom type RefundsPost it works and store data in the db but obviously without validation.
How can i fix?
Thx a lot
Not sure if this solves your problem, but I have rewritten your functions the way I would do it. You can specify what http method the rules are for, in this case I specified the rules for POST requests.
RefundsPost -> rules:
public function rules() {
$rules = [];
switch($this->method()) {
case 'POST':
{
$rules = [
'contr_nom' => 'required|max:255',
'contr_cog' => 'required',
'polizza' => 'required',
'email' => 'required',
'targa' => 'required',
'iban' => 'required|iban',
'int_iban' => 'required',
];
}
default:
break;
}
return $rules;
}
and in the storeRefundsData function, you should use $request->validated() and use the attributes it return after validation when you proceed the insertion.
RefundsController -> storeRefundsData:
public function storeRefundsData(RefundsPost $request) {
$attributes = $request->validated();
$customers = Customers::create($attributes);
if (!($customers instanceof Customers)) {
// could not create customer
return ['result' => false];
}
$customers = $customers->fresh(); // if you need to retrieve the objects id
return ['result' => true];
}
Unfortunately, I cannot comment.
However, out of curiosity the rule iban is custom I believe right?
If so, can you try the following:
public function rules()
{
return [
'contr_nom' => ['required', 'max:255'],
'contr_cog' => ['required'],
'polizza' => ['required'],
'email' => ['required'],
'targa' => ['required'],
'iban' => ['required', new Iban],
'int_iban' => ['required'],
];
}
Of course, don't forget to import the rule class at the top:
use App\Rules\Iban;
Try it and let us know, cheers!
Related
I'm trying to create a form to insert a user but the function doesn't work the second time, only the first. I got *rror after submitting it a second time.
302 found
UserController
class UserController extends Controller
{
// User
public function edit()
{
return view(
'pages.user.edit',
[
'user' => Auth::user(),
'title' => ''
]
);
}
public function create()
{
return view('pages.user.createUS', [
'levels' => Level::get(),
'perusahaans' => Perusahaan::get(),
'satkers' => Satker::get(),
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
public function store(Request $request)
{
// dd($validatedData);
$this->validate(request(), [
'name' => 'required',
'level_id' => 'required',
'satker_id' => 'required',
'username' => ['required', 'string', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'unique:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
]);
$errors = $this->errors();
if ($this->fails()) {
return redirect('users/create')->withErrors($errors)->withInput()->with('err', true);
}
// dd($validatedData, $request);
$user = new User([
'name' => request('name'),
'username' => request('username'),
'email' => request('email'),
'phonenumber' => request('phonenumber'),
'level_id' => request('level_id'),
'satker_id' => request('satker_id'),
'remember_token' => Str::random(10)
]);
$user->password = md5(request('password'));
$user->save();
return redirect()->route('users.create')->with('success', 'User Berhasil Dibuat!');
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
public function index()
{
$users = User::latest()->get();
$perusahaans = Perusahaan::get();
$satkers = Satker::latest()->get();
return view(
'pages.user.index',
[
'users' => $users,
'perusahaans' => $perusahaans,
'satkers' => $satkers,
'levels' => Level::get()
]
);
}
public function action(Request $request)
{
$pid = $request->post('pid');
$satkers = Satker::where('perusahaan_id', $pid)->latest()->get();
$html = '<option value="">Pilih Satuan Kerja</option>';
foreach ($satkers as $satker) {
$html .= '<option value="' . $satker->id . '">' . $satker->satker . '</option>';
}
echo $html;
// return response()->json(['html' => $html]);
}
// Setting Profile
public function show(User $user)
{
$details = DetailTransaksi::get();
$transaksis = Transaksi::latest()->get();
$tagihans = Tagihan::latest()->get();
$satkers = Satker::latest()->get();
// dd($tagihans->where('user_id', $user->id));
return view('pages.user.detail', [
'user' => $user,
'transaksis' => $transaksis,
'details' => $details,
'tagihans' => $tagihans,
]);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\User $user
* #return \Illuminate\Http\Response
*/
public function update(Request $request)
{
$user = Auth::user();
// $file_name = $request->image->getClientOriginalName();
$rules = [
'name' => 'required',
'username' => 'required',
'satker_id' => 'required',
'email' => 'required',
'phonenumber' => 'required',
'level_id' => 'required',
];
if (
$request->email != $user->email
) {
$rules['email'] = 'required|unique:users';
}
$validatedData = $request->validate($rules);
$validatedData['id'] = auth()->user()->id;
User::where('id', $user->id)
->update($validatedData);
return redirect('/user')->with('success', 'Profile has been Updated');
}
}
Blade
<section id="produk-form-create" class="">
<h4 class="fw-bold py-3 mb-4">
<span class="text-muted fw-light">User /</span> Tambah Data User
</h4>
<div class="col-xxl">
<div class="card mb-4">
<div class="card-header d-flex align-items-center justify-content-between">
<h5 class="mb-0">Form Tambah Produk</h5>
</div>
<div class="card-body">
<form action="/users/store" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6 mb-3 text-start">
<label for="name" class="form-label">Nama User</label>
<input id="name" type="name" name="name" value="{{ old('name') }}"
class="form-control #error('name') is-invalid #enderror" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="username" class="form-label">Username</label>
<input id="username" type="text" name="username" value="{{ old('username') }}"
class="form-control #error('username') is-invalid #enderror" required>
#error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="email" class="form-label">Email</label>
<input id="email" name="email" value="{{ old('email') }}" type="text"
class="form-control #error('email') is-invalid #enderror" required>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label for="leveluser" class="form-label">Level User</label>
<select class="form-select #error('leveluser') is-invalid #enderror" id="leveluser"
name="level_id" required>
#foreach ($levels as $level)
<option value="{{ $level->id }}">{{ $level->level }}</option>
#endforeach
</select>
#error('level_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="col-md-6 mb-3 text-start">
<label class="form-label" for="phonenumber">Phone Number</label>
<div class="input-group input-group-merge">
<span class="input-group-text">ID (+62)</span>
<input type="text" id="phonenumber" name="phonenumber" class="form-control"
placeholder="" value="{{ old('phonenumber') }}" required>
#error('phonenumber')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="perusahaan" class="form-label">Perusahaan</label>
<select class="form-select #error('perusahaan_id') is-invalid #enderror" id="perusahaan_id"
name="perusahaan_id" required>
#foreach ($perusahaans as $perusahaan)
<option value="{{ $perusahaan->id }}">{{ $perusahaan->nama_perusahaan }}
</option>
#endforeach
</select>
</div>
<input type="hidden" name="password" id="password" value="12345678">
<div class="col-md-6 mb-3 text-start">
<label for="password" class="form-label">Password</label>
<p>Password default untuk user adalah
<mark><strong
class="text-warning">"12345678"</strong></mark>
mohon arahkan kepada
user untuk mengganti password demi keamanan dan kenyamanan bersama.
</p>
</div>
<div class="col-md-6 mb-3 text-start">
<label for="satker_id" class="form-label">Satuan Kerja</label>
<select id="satker_id" name="satker_id"
class="form-select #error('satker') is-invalid #enderror" required>
#foreach ($satkers->where('perusahaan_id', 1) as $satker)
<option value="{{ $satker->id }}">
{{ $satker->satker }}
</option>
#endforeach
</select>
#error('satker_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row">
<div class="col-sm-4 ">
<button type="submit" class="btn btn-primary"><i class="fw-icons bx bx-send"></i>
Send
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
Routes
Route::get('users', [UserController::class, 'index'])->name('users')->middleware('userlevel');
Route::get('users/{user}/edit', [UserController::class, 'edit'])->name('users.edit')->middleware('userlevel');
Route::get('users/create', [UserController::class, 'create'])->name('users.create')->middleware('userlevel');
Route::post('/users/store', [UserController::class, 'store'])->name('users.store')->middleware('userlevel');
Route::delete('users/{user}/destroy', [UserController::class, 'destroy'])->name('users.destroy')->middleware('userlevel');
Route::put('users/{user}/update', [UserController::class, 'update'])->name('users.destroy')->middleware('userlevel');
Route::post('users/action', [UserController::class, 'action']);
Success in the first-time post but get 302 found in the second time. Please help me to solve this problem.
I have a simple form where the user should be able to only fill the inputs he wants but if the form hasn't at least one input filled, it should return a error message saying that the form can't be empty if he clicks the submit button.
Here's my form:
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<strong>{{ $message }}</strong>
</div>
#endif
</center>
<form action="{{ route('send-update') }}" method="POST" enctype="multipart/form-data"> #csrf
<label>Nome do projeto:</label>
<div class="input-group mb-3"><br>
<input type="text" class="form-control" name="project_name" aria-label="Username" aria-describedby="basic-addon1">
</div>
#error('project_name')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Descrição:</label>
<div class="input-group mb-3"><br>
<textarea class="form-control" name="desc" aria-label="With textarea"></textarea>
</div>
#error('desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem alguma imagem que queira mudar/inserir?</label>
<div class="input-group mb-3">
<input type="file" name="img" accept="image/*" class="form-control" id="inputGroupFile01">
</div>
#error('img')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<div class="input-group mb-3">
<input type="text" class="form-control" name="img_desc" placeholder="Diga-nos onde pretende mudar/adicionar">
</div>
#error('img_desc')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<label>Tem mais informações? Insira um arquivo .txt, docx ou pdf</label>
<div class="input-group mb-3">
<input type="file" name="ficheiro" accept=".xlsx,.xls,.doc, .docx,.ppt, .pptx,.txt,.pdf" class="form-control" id="inputGroupFile01">
</div>
#error('ficheiro')
<div class="text-danger" style="float:left; margin-top:-10px" role="alert">
<small> {{$message}}</small>
</div>
#enderror
<br>
<input type="hidden" name="id" value="{{ request('id') }}">
<center> <button type="submit" class="btn btn-secondary ">Fazer pedido de atualização</button></center><br>
</form>
And here's the controller:
public function sendUpdate(Request $request){
$id = $request['id'];
$order = Order::where('id', $id)->first();
$validator = Validator::make($request->all(), [
'project_name' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'img' => ['nullable', 'image', 'mimes:jpeg,png,jpg,svg', 'max:1024'],
'img_desc' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z]+$/u]'],
'ficheiro' => ['nullable', 'csv,txt,xlx,xls,pdf', 'max:2048'],
]);
if (request()->hasFile('ficheiro')){
if (request()->file('ficheiro')->isValid())
{
$fileName = $request->file('ficheiro')->getClientOriginalName();
$path = $request->file('ficheiro')->storeAs('files', $fileName, 'public');
}}
if (request()->hasFile('img')){
if (request()->file('img')->isValid())
{
$imageName = $request->file('img')->getClientOriginalName();
$pathImg = $request->file('img')->storeAs('files', $imageName, 'public');
}}
Update::create([
'customer_name' => $order->customer_name,
'customer_email' => $order->email,
'project_name' => $order->project_name,
'project_new_name' => $request['project_name'],
'description' => $request['desc'],
'image' => $pathImg ?? '',
'image_desc' => $request['img_desc'],
'ficheiro' => $path ?? '',
]);
return back()->with('success','Obrigado! Entraremos em contacto consigo em breve!');
}
I have no idea how to check if all inputs are empty in the controller . I've already tried this below, but it doesn't work. It keeps sending the form anyway.
if(count($request->all()) < 0) {
return dd('request all input empty.');
}
You can do it this way.
if(empty(array_filter($request->all()))){
//All fields are empty.
}
I have a custom regitration form where I need (users telephone number and company id) as well as email and password.
The telephone number and company id will get an api call to verify its existence in the comapny directory. If it passes then I need to allow User model to make the registration but if it fails then return a fail.
Q: where in the chain of registration should I make this api call to allow/reject the registration?
my \resources\views\auth\register.blade.php looks like this
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Register') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('register') }}">
#csrf
<div class="form-group row">
<label for="companyid" class="col-md-4 col-form-label text-md-right">Innovations ID</label>
<div class="col-md-6">
<input id="companyid" type="text" class="form-control" name="companyid" value="" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="telephonenumber" class="col-md-4 col-form-label text-md-right">Zip Code</label>
<div class="col-md-6">
<input id="telephonenumber" type="text" class="form-control" name="telephonenumber" value="" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email">
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
here is my controller app\Http\Controllers\Auth\RegisterController.php
I would think this is where I would add my api call but not sure how to go about it.
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct(){
$this->middleware('guest');
}
protected function validator(array $data){
return Validator::make($data, [
'companyid' => ['required', 'string', 'max:255'],
'telephonenumber' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
this is my user model app\User.php
protected $fillable = [
'companyid', 'telephonenumber', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
You need to do it in the create method of the RegisterController.
You can make api calls within create method using the Http facade. But you need to have guzzle as dependency in your project. You can pull it using composer.
composer require guzzlehttp/guzzle
Then you can make the api calls
protected function create(array $data)
{
//Remember to import the use statement
//use Illuminate\Support\Facades\Http; at top
$response = Http::get('http::/example.com');
//Need to stop further execution by throwing an exception
//If the verification via api call fails
//abort_unless($response->verified = true, 419);
return User::create([
'companyid' => $data['companyid'],
'telephonenumber' => $data['telephonenumber'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Laravel docs: https://laravel.com/docs/8.x/http-client#making-requests
I want to edit form update only address, email and password. How to change password? The old password is important.
edit.blade.php
<form method="POST" action="{{ route('update') }}">
#csrf
{{ method_field('PATCH') }}
<div class="form-group row">
<label for="email" class="col-md-1 col-form-label text-md-right">{{ __('Email') }}</label>
<div class="col-md-5">
<input id="email" type="text" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') ? : user()->email }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-1 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-5">
<input id="password" type="text" class="form-control #error('password') is-invalid #enderror" name="password" value="{{ old('password') }}" required autocomplete="password" autofocus>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="address" class="col-md-1 col-form-label text-md-right">{{ __('Address') }}</label>
<div class="col-md-5">
<textarea id="address" type="text" class="form-control #error('address') is-invalid #enderror" name="address" required autocomplete="address" autofocus>{{ old('address') ? : user()->address }}</textarea>
#error('address')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-1">
<button type="submit" class="btn btn-block btn-primary">
{{ __('Register') }}
</button>
</div>
</div>
</form>
Route
Route::post('update', 'Auth\RegisterController#sqlupdate')->name('update');
RegisterController
public function sqlupdate(Request $request)
{
Auth::user()->update([
'address' => $request['address'],
'email' => $request['email'],
]);
$hashedPassword = auth()->user()->password;
if (Hash::check($request->oldpassword, $hashedPassword)){
$user = User::findOrFail(Auth::id());
$user->password = Hash::make($request->password);
}
return redirect()->back();
}
Just read the below code carefully :-
/**
* Admin My profile : Password update.
*
* #param Request $request
* #param $id
* #return \Illuminate\Http\Response
*/
public function updatePassword(Request $request,$id = 0)
{
$validate = Validator::make($request->all(),[
'old_password' => 'required',
'password' => 'required|confirmed|min:8',
'password_confirmation' => 'required|min:8',
]);
$getUserData = Admin::where('id',$id)->first();
if($getUserData === null) {
return redirect()->back()->with([
'status' => 'warning',
'title' => 'Warning!!',
'message' => 'Invalid Admin ID.'
]);
}
$validate->after(function ($validate) use ($request,$getUserData,$id) {
if(!Hash::check($request->get('old_password'),$getUserData->password)){
$validate->errors()->add('old_password', 'Wrong old password');
}
});
if($validate->fails()){
return redirect()->back()->withErrors($validate)->withInput();
}
try{
$getUserData->update([
'password' => Hash::make($request->get('password'))
]);
return redirect()->back()->with([
'status' => 'success',
'title' => 'Success!!',
'message' => 'Admin password updated successfully.'
]);
}catch (Exception $e){
return redirect()->back()->with([
'status' => 'error',
'title' => 'Error!!',
'message' => $e->getMessage()
]);
}
}
With the above method you'll get the idea of how we update password, this is from one of my project i've created three field for that here is the screenshot of view :-
I hope this will help
Further more update here is the small snippet for update method
specially
$getOldPassword = User::where('id',$id)->first();
if($request->get('password') === null){
$password = $getOldPassword->password;
}else{
$password = Hash::make($request->get('password'));
}
i created a new controller called AuthController:
the authentication system that i created is not working :(
<?php
namespace App\Http\Controllers\Site;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function register(Request $request)
{
if ($request->isMethod('Get')) {
return view('auth.register');
}
$this->validate($request,[
'fname' => 'required|string|min:3|max:255',
'lname' => 'required|string|min:3|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|string|min:8|max:255|confirmed',
'username' => 'required|string|min:6|max:255|unique:users',
'mobile' => 'required|min:11|max:11|regex:/^09[0-3][0-9]{8}$/u|unique:users'
]);
$user = new User();
$user->fname = $request->fname;
$user->lname = $request->lname;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->username = $request->username;
$user->mobile = $request->mobile;
}
public function login()
{
return 'login';
}
public function logout()
{
}
}
and this is my Model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fname', 'lname', 'email', 'password', 'username', 'mobile'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
this is my registration form:
#extends('_partials.master')
#section('title','Register')
#section('stylesheet')
<link rel="stylesheet" href="/assets/css/slick-theme.css">
<link rel="stylesheet" href="/assets/css/slick.css">
<link rel="stylesheet" href="/assets/css/style.css">
#endsection
#section('content')
<article class="single-blog contact-us">
<div class="post-thumb">
<img src="assets/images/archi-feature-cat-6.jpg" alt="">
</div>
<div class="post-content">
<div class="entry-header text-center text-uppercase">
<h2 class="text-left">Register</h2>
</div>
<div class="entry-content">
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirtempor
invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</p>
</div>
<div class="leave-comment">
<form class="form-horizontal contact-form" method="post"
action="/register">
{{ csrf_field() }}
<div class="form-group">
<div class="col-md-6">
<input type="text" value="{{ #old('fname') }}" class="form-control" id="fname" name="fname"
placeholder="First Name">
<span class="text-danger">{{ $errors->first('fname') }}</span>
</div>
<div class="col-md-6">
<input type="text" value="{{ #old('lname') }}" class="form-control" id="lname" name="lname"
placeholder="Last Name">
<span class="text-danger">{{ $errors->first('lname') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('email') }}" class="form-control" id="email" name="email"
placeholder="Email">
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('username') }}" class="form-control" id="username" name="username"
placeholder="Username">
<span class="text-danger">{{ $errors->first('username') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<input type="password" value="{{ #old('password') }}" class="form-control" id="password" name="password"
placeholder="Password">
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
<div class="col-md-6">
<input type="password" value="{{ #old('password_confirmation') }}" class="form-control" id="password_confirmation" name="password_confirmation"
placeholder="Password Again">
<span class="text-danger">{{ $errors->first('password_confirmation') }}</span>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<input type="text" value="{{ #old('mobile') }}" class="form-control" id="mobile" name="mobile"
placeholder="Mobile">
<span class="text-danger">{{ $errors->first('mobile') }}</span>
</div>
</div>
<button type="submit" class="btn send-btn">Register</button>
</form>
</div>
</div>
</article>
#endsection
#section('javascript')
<script src="/assets/js/slick.min.js"></script>
<script src="/assets/js/main.js"></script>
#endsection
my register system dosnt work and it return a blank page.
it doesnt return any error.
i wanna make user Authentication system by myself.
what should i do?
plz help me
tnx
:)
After validating the data, use the create function like this:
$data = $request->all();
$user = User::create([
'fname' => $data->fname;
'lname' => $data->lname;
'email' => $data->email;
'password' => Hash::make($data->password);
'username' => $data->username;
'mobile' => $data->mobile;
]);
Auth::login($user); //this will login the user.
All your code is fine just change $this->validate($request to $this->validate($request->all(),
public function register(Request $request)
{
if ($request->isMethod('Get')) {
return view('auth.register');
}
$this->validate($request->all(),[
'fname' => 'required|string|min:3|max:255',
'lname' => 'required|string|min:3|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|string|min:8|max:255|confirmed',
'username' => 'required|string|min:6|max:255|unique:users',
'mobile' => 'required|min:11|max:11|regex:/^09[0-3][0-9]{8}$/u|unique:users'
]);
$user = new User();
$user->fname = $request->fname;
$user->lname = $request->lname;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->username = $request->username;
$user->mobile = $request->mobile;
$user->save(); //add this line
return redirect('login');
}
Add $user->save(); line