Using a php variable for validation in Laravel 4.2 - laravel

I have this code that gets an object in a session and i put it in a certain variable. Then i wanted to use it in the laravel 4.2 'same' validation. So far here is the code i have
session_start();
$getsCapt = $_SESSION["captcha"];
$rules = array(
'st' => 'required',
'capt' => 'required|numeric|same:$getsCapt'
);
It is not doing anything. What i wanted to have is i'll compare the value i get from the session with the value i get from the textbox in my view named 'capt' but so far its not doing anything. any ideas to do this properly?

First of all, You are using same validator incorrectly.
same expects a form field name
Example:
same:field_name
Where, the given field must match the field under validation.
You could register and use a Custom Validation Rule
Validator::extend('captcha', function($attribute, $value, $parameters)
{
$captcha = \Session::get('captcha');
return $value == $captcha;
});
So later you can do:
//session_start(); - Please no need for this in Laravel
//$getsCapt = $_SESSION["captcha"]; - Also remove this not necessary
$rules = array(
'st' => 'required',
'capt' => 'required|numeric|captcha'
);
NB:
Use Session::put to save something to session e.g \Session::put('something');
There is also Session::get for retrieving value from session e.g \Session::get('something');
Please avoid using $_SESSION not Laravel way of doing things
[Edited] Where to Register Custom Validation Rule?
There are basically two ways you can register a custom validation rule in Laravel.
1. Resolving from a closure:
If you are resolving through closure you can add it to : app/start/global.php
Validator::extend('captcha', function($attribute, $value, $parameters)
{
$captcha = \Session::get('captcha');
return $value == $captcha;
});
2. Resolving from a class
This is the best and preferred way of extending custom validation rule as its more organised and easier to maintain.
i. Create your own validation class, CustomValidator.php, maybe in app/validation folder
<?php namespace App\Validation;
use Illuminate\Validation\Validator;
use Session;
class CustomValidator extends Validator{
public function validateCaptcha($attribute, $value, $parameters)
{
$captcha = Session::get('captcha');
return $value == $captcha;
}
}
NB: Notice the prefix validate used in the method name, validateCaptcha
ii. Create a Service Provider that will resolve custom validator extension in app/validation folder
<?php namespace App\Validation;
use Illuminate\Support\ServiceProvider;
class CustomValidationServiceProvider extends ServiceProvider {
public function register(){}
public function boot()
{
$this->app->validator->resolver(function($translator, $data, $rules, $messages){
return new CustomValidator($translator, $data, $rules, $messages);
});
}
}
iii. Then add CustomValidationServiceProvider under app/config/app.php providers array:
'providers' => array(
<!-- ... -->
'App\Validation\CustomValidationServiceProvider'
),
iv. And add the custom error message in app/lang/en/validation.php
return array(
...
"captcha" => "Invalid :attribute entered.",
...
)

Change single quotes to double quotes
$rules = array(
'st' => 'required',
'capt' => "required|numeric|same:$getsCapt"
);
Or simply concatenate the value
$rules = array(
'st' => 'required',
'capt' => 'required|numeric|same:' . $getsCapt
);

Related

Laravel Validator - Check custom validation rule after other rules get checked

How are you? Hope you are doing great
I need one help for Laravel Validator, i have created one custom validation rule like below
$validation = Validator::make($request->all(), [
'user_id' => 'required',
'role' => ['required', new RoleExist($request->user_id)],
]);
See i have passed one argument to rule's constructor new RoleExist($request->user_id) but laravel giving me 500 error if i do not pass user_id in the request
The error is
Argument 1 passed to App\Rules\RoleExist::__construct() must be of the type integer, null given
I know user_id is not passed in the request so laravel giving above error, but here my custom rule should be execute after 'user_id' => 'required',
Custom Rule Code
private $userId;
public function __construct(Int $userId)
{
$this->userId= $userId;
}
public function passes($attribute, $value)
{
return empty(\App\User::where('user_id', $this->userId)->where('status', '1')->first());
}
Is there any way to do the same
Thank you in advance

How to convert object return by laravel model factory create method into array containing model fields?

For example, I have a UserFactory.php
<?php
use App\User;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'email_verified_at' => now(),
'role' => 'USER',
'password' => 'sasdcsdf34', // password
'remember_token' => Str::random(10),
];
});
Now, I can create a user as following
$user = factory(User::class)->create();
Now, How can I convert this $user object into array containing user info like name,email etc without initializing new array and manually assigning every $user object property. ??
I DON'T want to manually assign like following as it is tedious if there are many properties in $user object
$userArray=[
'id' => $user->id,
'name' => $user->name,
'email' => $user->email
]
I have tried this but it creates array containing various other properties and actual values needed are nested inside properties
$userArray=array($user)
You should try using the raw method of factory instead of create.
$user = factory(User::class)->raw();
This should give you an array you can work with.
Try to add something like this to your model class:
public function getArr(){
foreach($this->attributes as $key => $val){
$array[$key] = $val;
}
return $array;
}
If you wish to have this function in every model you could create trait with this function and then just attach it in model class or any class extending it.
You can use json_decode.
// Laravel 7
$userArray = json_decode(factory(User::class)->create(), true);
// Laravel 8
$userArray = json_decode(User::factory()->create(), true);
For Laravel 8, instead of make or create method, use:
User::factory()->raw();
This will return an array

Laravel Email Verification in custom registeration controller not working

I have made a registration form in my frontend ( Not a laravel default registration form ) . I have used Laravel Email Verification
I have implements MustVerifyEmail in User Model
But In that custom registraion form in my frontend when i hit submit it redirects the page to /admin/home but email is not been sending when i register but If I click on resend email again it sends the email . I want to fix that
Does anyone know how ?
Do I have to implements MustVerifyEmail to that controller too or what ?
IGNORE THAT CITY AND ROOM IN THE FUNCTION !!!!!
class QuickRegisterController extends Controller
{
public function quickList(Request $request)
{
$this->validate($request ,[
'features' => 'required',
'rommies' => 'required',
'price' => 'required',
'avaiability' => 'required',
'utility' => 'required',
'owner_working_email' => 'required',
'address' => 'required',
'exact_address' => 'required',
'owner_of_the_room' => 'required',
]);
$user = User::firstOrCreate([
'name' => $request->owner_of_the_room,
'email' => $request->owner_working_email,
'password' => bcrypt($request->password),
'role_id' => config('quickadmin.default_role_id'),
]);
\Auth::loginUsingId($user->id);
if (\Auth::check()) {
$city = TotalCity::firstOrCreate([
'name' => $request->city,
'created_by_id' => \Auth::user()->id,
]);
if ($city) {
$room = new MyRoom;
$room->location_id = $city->id;
$room->features = $request->features;
$room->rommies = $request->rommies;
$room->price = $request->price;
$room->utility = $request->utility;
$room->avaiability = $request->avaiability;
$room->owner_woring_email = $request->owner_working_email;
$room->address = $request->address;
$room->exact_address = $request->exact_address;
$room->owner_of_the_room = $request->owner_of_the_room;
$room->save();
}
return redirect('/admin/home');
}
else {
return redirect()->back()->with('Form Submission Failed . Try Again Later');
}
}
}
If you look into the RegisterController that Laravel provides with its auth scaffolding, not sure if you are using that or not, it implements the RegistersUsers trait. That trait implements an event that is triggered upon registration. You can use the RegistersUsers trait in your class or create your own custom event.
I'll show you how to use the trait.
At the top of your file:
use Illuminate\Foundation\Auth\RegistersUsers;
Right inside your class:
use RegistersUsers;
For Example:
use Illuminate\Foundation\Auth\RegistersUsers;
class QuickRegisterController extends Controller
{
use RegistersUsers;
// ....
}
You'll need to set up the route as well.
// The register method is coming from the trait
Route::post('/register', 'QuickRegisterController#register');
Also,
You'll want to update your method name to create, the trait calls a create method from the implementor, which is where the user gets created and then the event is triggered, and in that create a method just return the new user, instead of redirecting back.
This might not be all you need to do to get this working, but it will get you started. If you are interested in creating your own event:
https://laravel.com/docs/5.8/events
Or, as #Bipin Regmi pointed out you can just use the event that is being used in the trait
event(new \Illuminate\Auth\Events\Registered($user = $this->create($request->all())));

Validating fields as unique in cakephp 3.0

How do you validate a field is unique in cakephp 3.0? There doesn't appear to be a validation function listed in the API.
You want to use the rule validateUnique. For example, to check an email address is unique on an UsersTable:-
public function validationDefault(Validator $validator)
{
$validator->add(
'email',
['unique' => [
'rule' => 'validateUnique',
'provider' => 'table',
'message' => 'Not unique']
]
);
return $validator;
}
Details can be found in the API docs.
you have to use the rules from cake's ORM on your table...
add this at the top of your UsersTable after your namespace
use Cake\ORM\Rule\IsUnique;
Then prepare your rule to apply to your field by placing it in a public function
public function buildRules(RulesChecker $rules){
$rules->add($rules->isUnique(['email']));
return $rules;
}
Consult the cakephp documentation for more information about RULES
Validation providers can be objects, or class names. If a class name is used the methods must be static. To use a provider other than ‘default’, be sure to set the provider key in your rule:
// Use a rule from the table provider
$validator->add('title', 'unique', [
'rule' => 'uniqueTitle',
'provider' => 'table'
]);
For more details, look at the Adding Validation Providers section in the CakePHP3 reference book.
Use application rules as described in manual.
Kindly please check this for unique validation in cakephp 3.8
go to site
public function validationDefault(Validator $validator)
{
$validator->requirePresence('login_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['login_id'], 'User already exist.'));
return $rules;
}

How to specify the default error message when extending the Validation class in Laravel 4

I use made use the extend function to extend and adding custom rules on the Validation Class of Laravel 4.
Validator::extend('foo', function($attribute, $value, $parameters)
{
return $value == 'foo';
});
When I validate the rule using the newly created custom extension, it returns validation.foo if the rule fails. Is there a way to define a generic/ default message when extending the validation class in Laravel 4?
The Laravel 4 docs specifically state you need to define an error message for your custom rules.
You have two options;
Option 1:
$messages = array(
'foo' => 'The :attribute field is foo.',
);
$validator = Validator::make($input, $rules, $messages);
Option 2:
Specify your custom messages in a language file instead of passing them directly to the Validator. To do so, add your messages to custom array in the app/lang/xx/validation.php language file:
'custom' => array(
'foo' => array(
'required' => 'We need to know your foo!',
),
),
In case someone is wondering about Laravel 5: just add your message to validation.php right under all the default messages. For example:
<?php
return [
// .. lots of Laravel code omitted for brevity ...
"timezone" => "The :attribute must be a valid zone.",
/* your custom global validation messages for your custom validator follow below */
"date_not_in_future" => "Date :attribute may not be in future.",
where date_not_in_future is your custom function validateDateNotInFuture.
Laravel will pick the message each time you use your rule for any field and you won't have to use custom array unless you want to override your global message for specific fields.
Full code to implement the validator follows.
Custom Validator (with a bonus gotcha comments for date_format and date_before localization):
<?php namespace App\Services\Validation;
use Illuminate\Validation\Validator as BaseValidator;
/**
* Class for your custom validation functions
*/
class Validator extends BaseValidator {
public function validateDateNotInFuture($attribute, $value, $parameters)
{
// you could also test if the string is a date at all
// and if it matches your app specific format
// calling $this->validateDateFormat validator with your app's format
// loaded from \Config::get, but be careful -
// Laravel has hard-coded checks for DateFormat rule
// to extract correct format from it if it exists,
// and then use for validateBefore. If you have some unusual format
// and date_format has not been applied to the field,
// then validateBefore will give unpredictable results.
// Your best bet then is to override protected function
// getDateFormat($attribute) to return your app specific format
$tomorrow = date('your app date format here', strtotime("tomorrow"));
$parameters[0] = $tomorrow;
return $this->validateBefore($attribute, $value, $parameters);
}
}
ValidatorServiceProvider file:
<?php namespace App\Providers;
namespace App\Providers;
use App\Services\Validation\Validator;
use Illuminate\Support\ServiceProvider;
class ValidatorServiceProvider extends ServiceProvider{
public function boot()
{
\Validator::resolver(function($translator, $data, $rules, $messages)
{
return new Validator($translator, $data, $rules, $messages);
});
}
public function register()
{
}
}
And then just add a line to config/app.php:
'App\Providers\RouteServiceProvider',
'App\Providers\ValidatorServiceProvider', // your custom validation
In addition to what TheShiftExchange has said, if you look in that validation.php language file you'll see all of the different rules that you can specify. So for instance, if your validator has entries like this:
class ArticleValidator extends Validator
{
public static $rules = [
'create' => [
'title' => ['required'],
'slug' => ['required', 'regex:([a-z\0-9\-]*)']
]
];
}
Then your custom validation rules may look like this:
'custom' => array(
'company_article_type_id' => array(
'required' => 'The slug field is really important',
'exists' => 'The slug already exists',
),
),
Notice how the 'required' and 'exists' keys in the custom validation rules match those in the validator above.

Resources