validation usage in laravel 4 - validation

I am working with Laravel 4 validation right now. My basic setup is done and tested. I can fill the form in view and submit to controller. I can save all details to database using model. I am having a problem now with validation.
I use Input::get() to capture each of the posted variables in the controller. I read that validation should ideally be done in the model. where am I supposed to invoke the validator? Model or Controller? and how am I supposed to pass the validator the $input? is it an array of all variables posted or am I missing something?
Laravel 4 documentation really fails to illustrate with examples answers to common usage questions.
This is the validator I set up in my model:
public static function validate($input)
{
$rules = array(
# place-holder for validation rules
'firstname' => 'Required|Min:3|Max:40|Alpha',
'lastname' => 'Required|Min:3|Max:40|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'country' => 'Required',
'password' =>'Required|AlphaNum|Between:7,15|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:7,15'
);
# validation code
$validator = Validator::make($input, $rules);
/*if( $validator->passes() ) {
} else {
# code for validation failure
}*/
}
controller:
public function register()
{
/*Create new user if no user with entered email exists. Use validator to ensure all fields are completed*/
$user = new User;
/*Handle input in POST*/
$email = Input::get('email');
$password = Input::get('password');
$passwordConfirmed = Input::get('password_confirmation');
$firstName = Input::get('firstname');
$lastName = Input::get('lastname');
$country = Input::get('country');
$user->email = $email;
$user->password = Hash::make($password);
$user->firstname = $firstName;
$user->lastname = $lastName;
$user->country = $country;
//$user->save();
$this->layout->content = View::make('test');
}
and I've been following this link so far when it comes to validation. Please help as I am new to this framework

You are missing the input in the validator, you did not defined it
Use it like
$input = Input::all();
$validator = Validator::make($input, $rules);
or
$validator = Validator::make(Input::all(), $rules);
and take a look at the forums, this will help you more than that blog: http://forums.laravel.io/viewtopic.php?id=12104

Related

Is usage of return value of laravel's validate important?

let's imagine this code.
public function store(Request $request) {
$validated = $request->validate(['name' => 'required']);
$post = new Post();
$post->name = $request->name;
// OR
$post->name = $validated['name'];
$post->save();
}
is it important to use $validated['name'] as opposed to $request->name?
i was testing some basic sql injections and my app seemed to be protected even with $request->name
so is $request validated?
As #Tim Lewis said they are the same
because if the validation didn't pass it will not continue to the rest of your code inside the controller's method
the most common case to use the validated array is when you try to create new model or update one and you want to add each property manually so you could just pass it directly like this
$validated = $request->validate([
'title' => 'required',
'body' => 'required'
]);
Post::create($validated);

How to send password set(reset link) laravel 7

I was trying to send a password reset link to my newly created user and had a hard time trying to find a solution. In case someone has the same issue here is what worked for me in Laravel 7.
Or is there a better way to handle all: add entry in password_resets table and send the notification?
Mail sending properly but i want to send password reset mail to user .Below is the my add controller
public function contactSave(Request $request)
{
$password = Hash::make($request->name);
$validate = $request->validate([
'name' => 'required|regex:/^[\pL\s\-]+$/u',
'email' => 'email',
'phone' => 'digits:10',
'address' => 'required',
'country' => 'required',
'state' => 'required',
// 'comment' => 'required',
'organization' => 'required',
'captcha' => 'required|captcha'
],
[
'captcha.captcha' => 'Incorrect Captcha'
]
);
$user= new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $password;
$user->save();
$CustomerContact= new CustomerContact;
// $CustomerContact->name = $request->name;
// $CustomerContact->email = $request->email;
$CustomerContact->phone = $request->phone;
$CustomerContact->address = $request->address;
$CustomerContact->user_id = $user->id;
$CustomerContact->country_id = $request->country;
$CustomerContact->state_id = $request->state;
$CustomerContact->comment = $request->comment;
$CustomerContact->organization = $request->organization;
$CustomerContact->captcha = $request->captcha;
$CustomerContact->save();
$details = [
'title' => 'Hi '.$request->name.'',
'body' => 'Your account has been created successfully. Request you set your password with this link ???'
];
\Mail::to($request->email)->send(new \App\Mail\ContactMail($details));
return redirect('contacts')->with('success', 'User created successfully.');
}
Anyone here to help me. After saving data in user and employee . I want send email with password reset link to that user id email($request->email).
GIve me simplest solution with kittle explation how to do this
if i correctly understood your problem you can create a route for example: password/reset/user-code
and send it in your email to every user.
you should create a random-code for every user when its created and put it in that link and send in your email.
when user click on that link it will come to your controller and you check that random-code in your database and find your user! and when you have your user you can show them your view for resetting password and save new password
that what i did for password reset before
IF you want to send some data (link or token or everything else) to your mail use this:
Mail::to($request->email)->send(new ContactMail($your_token,$link,$user));
and in your ContactMail class:
class ContactMail extends Mailable
{
use Queueable, SerializesModels;
public $your_token;
public $link;
public $user;
public function __construct($your_token,$link,$user)
{
$this->your_token= $your_token;
$this->link= $link;
$this->user= $user;
}
public function build()
{
return $this->view('email')
->with('your_token',$this->your_token)
->with('link',$this->link)
->with('user',$this->user
}
}

Laravel unique rules on update, not working properly

From This answer I am trying to update department data. Code as below :
$id = Crypt::decrypt($id);
$rules = Department::$rules;
$rules['name'] = $rules['name'] . ',id,' . $id;
$rules['department_code'] = $rules['department_code'] . ',id,' . $id;
dump($rules);
$validator = Validator::make($data = $request->all(), $rules);
if ($validator->fails()) return Redirect::back()->withErrors($validator)->withInput();
$department = Department::findOrFail($id);
But the validator says :
The department code has already been taken.
The name has already been taken.
So whats wrong ?
My rules array is:
public static $rules = [
'name' => 'required|unique:departments|max:255',
'department_code' => 'required|unique:departments|max:127',
];
Change your $rules array as:
public static $rules = [
'name' => 'required|max:255|unique:departments',
'department_code' => 'required|max:127|unique:departments',
];
Then you can use it to append id in the rules.

Getting an id after mass asignment

Ok so we can create a new user:
$user = new User;
$user->name = 'Megauser'
$user->save();
And then we can add some user items:
$item = new Item;
$item->user_id = $user->id; //id we got from a freshly created user
$item->quantity = '9000';
$item->save();
But what if we mass assign the user?
User::create([
'name' => 'Megauser'
)];
The create method will return the new object with its ID.
$user = User::create([
'name' => 'Megauser'
)];
$userId = $user->id
Or as Rob Gordijn pointed out below, if you are worried about key names, you can use the getKey() call.
$userId = $user->getKey();
This is necessary if someone overrides the column name in their Eloquent model. For example:
class Example extends Eloquent {
$primaryKey = 'uid';
}
$user = User::create([
'name' => 'Megauser'
)];
I would go for
<?php
$User = User::create([
'name' => 'Huzzah'
)];
$UserKey = $User->getKey();
to ensure your still works when someone decides to changes the column name ;)

How to check for unique key when saving object to database in laravel?

I'm trying to save to a database, I wish to ignore the post if it's already in the database. This is how I currently save it. The postid has to be unique.
public function save($type, $postid, $url, $author, $content)
{
$post = new Post;
$post->type = $type;
$post->postid = $postid;
$post->url = $url;
$post->author = $author;
$post->content = $content;
echo $post;
$post->save();
}
Use the Validator class' unique validation rule on whatever fields you wish to be unique before trying to save.
$input = array('postid' => $postid);
$rules = array(
'postid' => 'unique:posts,postid'
);
$validate = Validator::make($input,$rules);
if($validator->passes())
{
$this->save($type, $postid, $url, $author, $content)
}
else
{
$messages = $validator->messages();
echo $messages->first('postid');
}
You can use Post::findOrFail(UNIQUE_ID) using it in a try ... catch ... structure to fallback if a post has already this unique ID you want to set.
You can check unique in validation. I'm not sure if you are checking unique primary postid. I would suggest you to keep postid as primary key & auto increment. You can match the post title for duplication.
$rules = array(
'postid' => 'required|unique:posts'
);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::back()->withInput()->with('errors', $validator->messages());
}else{
$data = array(
'type' => Input::get('type'),
'postid' => Input::get('postid'),
'url' => Input::get('url'),
'author' => Input::get('author'),
'content' => Input::get('content')
);
if(Post::create($data)){
Session::flash('messages', 'Post created.');
return Redirect::route('routename');
}
}

Resources