How to check if in inside validtion request? - laravel

I have this validation request:
public function rules()
{
return [
'user_id' => ['required', 'exists:users,id'],
'address_type' => ['required', 'in:main_address,new_address'],
'governorate_id' => ['required', 'exists:governorates,id'],
'area_id' => ['required', 'exists:areas,id'],
'phone' => ['required', 'string', 'max:15'],
'nearly_area' => ['required', 'string', 'max:200'],
];
}
How can check if the user choose in address_type (main_address one) ignore the rest of fields and if new_address the rest fields should be required ??

Use required_if like:
public function rules()
{
return [
'user_id' => ['required', 'exists:users,id'],
'address_type' => ['required', 'in:main_address,new_address'],
'governorate_id' => ['required_if:address_type,==,new_address', 'exists:governorates,id'],
'area_id' => ['required_if:address_type,==,new_address', 'exists:areas,id'],
'phone' => ['required_if:address_type,==,new_address', 'string', 'max:15'],
'nearly_area' => ['required_if:address_type,==,new_address', 'string', 'max:200'],
];
}

Related

How to take User Id from Request(rules) for update?

Could I know how to take the user Id to Request an update? for example, when I updated the user and password. But, except email. At that time, It showed "the message that the email is already taken. When I searched for solutions, I found to solve with the user id. I know this question is asked many times. But, I didn't get any suitable answer for me. Could you help me, please?
This is my Controller Code
public function edit(Users $request,$id){
$users=User::whereId($id)->firstorFail();
$users->name = $request->get('name');
$users->email = $request->get('email');
$users->password = Hash::make($request->get('password'));
$users->role = $request->get('role');
$users->update();
$request->session()->forget('editvalue');
$userdata = User::paginate(4);
// session()->flash('status', 'User has been successfully added.');
return view('pages.auth.register', compact('userdata'))->with('status','User has been successfully added.');
}
This is my Request Form. I want to take id value in this. When I take value, it is showing the message that Trying to get property 'id' of non-object
public function rules() {
return [
'name' => 'required', 'string', 'max:255',
'email' => 'sometimes','required', 'string', 'email', 'max:255', 'unique:users,'. $this->users->id,
'password' => 'required', 'string', 'min:8', 'confirmed',
'role' => 'required', 'string',
];
}
This is my web.php
Route::get('users/edit/{id}', 'UsersController#editscreen');
Route::post('users/edit/{id}', 'UsersController#edit');
You should also put the column name to the rule,
the pattern should be unique:table,column,except_id
Can you replace your RequestForm with this:
public function rules()
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['sometimes','required', 'string', 'email', 'max:255', 'unique:users,email,'. $this->users->id],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'role' => ['required', 'string'],
];
} }
I think you can't validate {id} in the request class but you can validate with regex in the route. (My Example is for laravel 8 but the principle remains the same)
Route::post('/users/edit/{id}', [UsersController::class, 'editscreen'])
->where('id', '[0-9]+');
I got with this.
use Illuminate\Validation\Rule;//import Rule class
public function rules()
{
return [
'name' => 'required', 'string', 'max:255',
'email' => ['sometimes','required', 'string', 'email', 'max:255',
Rule::unique('users')->ignore($this->id),
],
'password' => 'required', 'string', 'min:8', 'confirmed',
'role' => 'required', 'string',
];
}
I just encountered this problem and managed to solve by adding $this->id only.
public function rules()
{
return [
'name' => ['required', 'string', 'max:255']
'email' => ['required', 'string', 'unique:users,email,' . $this->id]
];
}

How to redirect failed validate on register to an url with anchor in laravel jetstream fortify

If I change validate by validator->fails return redirect..... I get error because login want an instance of $user and I send a response.
This defaults work well but not for me
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
Thats give me a:
Illuminate\Auth\SessionGuard::login(): Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, Illuminate\Http\RedirectResponse given, called in ....endor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php on line 57
public function create(array $input)
{
$validator = Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
]);
if($validator->fails()) {
return Redirect::to(URL::previous() . "#my-anchor")->withInput()->with('error', $validator->messages()->first());
} //Thats I want
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
I don't did this before but maybe you can find the way to customize it. The CreateNewUser is called in the RegisteredUserController's store method, and the first return an User's instance. So in this you can
if($validation->fails())
return $validation->messages()->first();
and in the store method
public function store(Request $request, CreatesNewUsers $creator): RegisterResponse
{
$user = $creator->create($request->all()));
if($user instanceof User::class) {
event(new Registered($user);
$this->guard->login($user);
return app(RegisterResponse::class);
} else
return Redirect::to(URL::previous()."#my-anchor")->withInput()->with('error', $user);
}
Try this, but I suggest you if works extends this Register controller and just modify this store method

How can I redirect to function controller after registration in laravel 8

I hope you can help me, I wanna customize the registercontroller from Laravel, I have this, but after the user is registered send me a JSON of data, how can I do for don't send me the JSON and redirect to the HomeController.
Thanks.
PD. Sorry for my English.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
return User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
return redirect()->action('HomeController#index'),
]);
}
Laravel 5.5: Execute a method before registration
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('index');
}
}
You are returning the return value of User::create() which will be a User object which gets converted to json when returned as a response.
Also since your HomeController is protected by 'auth' middleware you need to login the user before redirecting to '/home'
use Illuminate\Support\Facades\Auth;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
$user = User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
]);
Auth::guard()->login($user);
return redirect('/home');
}
Move the redirect after create user , try like this
User::create([
'name' => $request->input('name'),
'nombre' =>$request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password'])
]);
return redirect()->action('HomeController#index'),

Validation fails even if it has values Maatwebsite Laravel Validation

I'm currently using Maatwebsite collection when processing the import CSV file and validating it as well since I'm having hard time using the ToModel way. Here's how I validate the csv fields:
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
\Validator::make($row->toArray(), [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
This is a sample data I have.
Illuminate\Support\Collection {#565 ▼
#items: array:6 [▼
0 => "Room name"
1 => "Room101"
2 => "user"
3 => "fmacejkovic#example.org"
4 => "password"
5 => "remarks"
]
}
My problem now is that even though the values are all correct and valid, it still fails in the validation. I'm trying to assign to a specific variable so that when it fails, it'll return the row name instead of row number. Even though I use the row number, it still fails.
You have used incorrect syntax for Validator::make(), use this :
class ImportRooms implements ToCollection, WithStartRow
{
public function collection(Collection $rows)
{
foreach($rows as $row){
$row = $row->toArray();
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5],
];
\Validator::make($data, [
'name' => ['required', 'max:50'],
'room_code' => ['required', 'max:50'],
'user_name' => ['required', 'max:255'],
'email' => ['required', 'email', 'max:255','nullable'],
'password' => ['min:8','max:255','nullable'],
'remarks' => ['max:500'],
])->validate();
}
}
/**
* #return int
*/
public function startRow(): int
{
return 2;
}
}
Refer https://laravel.com/docs/5.8/validation#automatic-redirection
//Convert row data into array and store it in a variable.
$row = $row->toArray();
//Set data to be validated.
$data = [
'name' => $row[0],
'room_code' => $row[1],
'user_name' => $row[2],
'email' => $row[3],
'password' => $row[4],
'remarks' => $row[5]
];
//Set conditions for validation.
$conditions = [
'name' => 'required|max:50',
'room_code' => 'required|max:50',
'user_name' => 'required|max:255',
'email' => 'required|email|max:255|nullable',
'password' => 'min:8|max:255|nullable',
'remarks' => 'max:500'
];
//Validate the excel data.
\Validator::make($data, $conditions)->validate();

How to create unique column in registration validator for two different tables

I'm creating two different registration (for admin and user). But the username->unique in the validator is only for table users.
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => ['required', 'string', 'max:255', 'min:3'],
'middlename' => ['required', 'string', 'max:255', 'min:3'],
'lastname' => ['required', 'string', 'max:255', 'min:3'],
'username' => ['required', 'string', 'max:255', 'min:3', 'unique:users'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
validate unique username for user registration from the users table and validate unique username for admin registration from the admins table.
You could use the route name or something similar, from the current request to determine which rules have to get used.
protected function validator(array $data)
{
$route = Request::route()->getName();
$rules = [
'firstname' => ['required', 'string', 'max:255', 'min:3'],
'middlename' => ['required', 'string', 'max:255', 'min:3'],
'lastname' => ['required', 'string', 'max:255', 'min:3'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
];
// whatever your route name or identifier to differentiate between
// user and admin registration may be.
if ($route === 'registration.user') {
$rules = $rules + [
'username' => ['required', 'string', 'max:255', 'min:3', 'unique:users'],
];
}
return Validator::make($data, $rules);
}
A Validator should only validate data, it's bad to couple it with concepts about routes etc...
I would create a custom Validator class which will take a table name as parameter.
Then you can instantiate that validator with the correct table parameters in your controller (which will be aware about route, request etc...)

Resources