How to update without changing the value of unique fields? - php

I update user data. Form of update is fill current user data. And if I don't change email validation show me error that this email already been taken. I use Rule::unique that resolve this problem but this not working ?

Fix previous answer
class CustomerRequest extends FormRequest
{
public function rules()
{
return [
'first_name' => 'min:3|max:20|regex:/^[a-zA-z-0-9]+$/u',
'last_name' => 'min:3|max:30|regex:/^[a-zA-z-0-9]+$/u',
['email', Rule::unique('customers')->ignore($this->customer->id)]
];
}
Also in your controller must receive
public function update(CustomerRequest $request, Customer $customer)
{
//Code
}

Related

Laravel 8: Checking user's data with database table does not work properly

I have created a two factor authentication system, and it redirects user to token.blade.php where he must enters the token that is going to be sent to his phone number and also stored at active_codes table.
Now I want to check if the user has entered the same token code that was stored at active_codes table which looks like this:
And then at the Controller, I tried this:
public function submit(Request $request)
{
$data = $request->validate([
'token' => 'required|min:6'
]);
if($data['token'] === auth()->user()->activeCode()->code){
dd('same');
}
}
But when I enter the same token, I get this error:
ErrorException Undefined property:
Illuminate\Database\Eloquent\Relations\HasMany::$code
so my question is how to check if the requested token code of user, is as same as the token code which is stored on the DB ?
Note: The relationship between User and ActiveCode Models is OneToMany.
User.php:
public function activeCode()
{
return $this->hasMany(ActiveCode::class);
}
ActiveCode.php:
public function user()
{
return $this->belongsTo(User::class);
}
Your solution is pretty easy, you are not doing ->first() or ->get(), so you are trying to access a model property on a HasMany class.
This code should be similar to:
auth()->user()->activeCode()->first()->code
But if you have more than 1 code, then you should do something like:
public function submit(Request $request)
{
$data = $request->validate([
'token' => 'required|min:6'
]);
if(auth()->user()->activeCode()->where('code', $data['token'])->exists()){
dd('same');
}
}

Laravel unique ruleset ignores the current user id

I'm working on updating a user in Laravel, where I made the following validation rule for updating a users email:
"email" => "required|email|unique:users,email,".$this->route("user")->id,
This is inside of my form request.
However, when I post, it still says that the email is already taken? Is this perhaps a bug in the latest version of Laravel?
Thanks!
No it is not a bug, you are using a null value for the id hence the reason why, change your rule to this:
"email" => "required|email|unique:users,email,".$this->user()->id,
Make sure that you have Request $request in your method, and also you have the auth middleware on your controller.
you set the ignore email column so you should pass email not id
"email" => "required|email|unique:users,email,".$this->route("user")->email,
First you have to add rules in user model
static function rules() {
return [
'email' => 'required|email'
];
}
In user controller
use Illuminate\Validation\Rule; // add this one
function add_update_user(Request $request,$user_id) {
$data = $request->all();
unset($data['_token']);
$rules = User::rules();
$rules['email'] = explode('|', $rules['email']);
if (isset($user_id)) // is old user, your get user_id in route
{
$rules['unique_code'][] = Rule::unique('databse_connection_name.users')->ignore($data['email'], 'email');
} else // is new user
{
$rules['email'][] = 'unique:databse_connection_name.users,email';
}
$validator = Validator::make($data, $rules);
...
...
}

Laravel 5 make a custom register function

Laravel 5 has it's default register function which is in
public function postRegister(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}
I know that I can copy this code and paste it in my AuthController but there's a change that I need to make which I don't know where to start and find. What I want is change the code for the insertion of data in my users table. I want to change this because I add another column in my users table which is company_name and I have a table which is named companies so basically when the user enter a company_name for registration it will check the companies table if it is existing then return error message if it is. So think there is something like:
$rules = array(
'company_name' => 'unqiue:companies',
);
But i don't know where to put this thing in my registration code. Thanks
You can use a custom validation, in this case. Make sure, you a are calling $this->validate(), and not $this->validator. This validate will automatically redirect back with errors if it fails, so you can skip the check statement.
public function postRegister(Request $request)
{
$this->validate($request->all(), [
'company_name' => 'unique:companies',
// And the other rules, like email unqiue, etc..
]);
Auth::login($this->create($request->all()));
return redirect($this->redirectPath());
}

Can you populate an Eloquent model without creating an entry in the database using Laravel 5

When I'm adding or editing an entry to my database table websites I load the instance of the website to be modified (or a blank one for creating a website). This works great, this is my controller:
<?php namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use App\Models\User;
use App\Models\Status;
use App\Models\Website;
class WebsitesController extends Controller {
/**
* Show / Process the create website form to the user.
*
* #return Response
*/
public function create()
{
$statuses = Status::all();
$users = User::all();
$website = Website::find(0);
return view('admin/websites/create', [
'statuses' => $statuses,
'users' => $users,
'website' => $website
]);
}
public function update($id)
{
$statuses = Status::all();
$users = User::all();
$website = Website::findOrFail($id);
return view('admin/websites/update', [
'statuses' => $statuses,
'users' => $users,
'website' => $website
]);
}
}
The problem is when I submit the form and there is an error. The user is returned to the page and the errors displayed. I also pass the users input back so I can repopulate the form with what they entered. But how can I replace the values in website with the values from input if it's present without actually saving to the database? I've been playing around with this all day and not found a working solution.
My create method is this:
public function postCreate(Request $request)
{
$v = Validator::make($request->all(), Website::rules());
if ($v->fails())
{
return redirect()->back()->withInput()->withErrors($v);
}
$website = Website::create($request->all());
return redirect()->action('Admin\HomeController#index')->with('messages', [['text' => 'Website created', 'class' => 'alert-success']]);
}
I'm passing the input back to the original form, but the form populates its values from the Website Eloquent model. **How can I get the input from $request->all() into $website?
I've tried using fill(), but I just get Call to a member function fill() on null when using it in the create function.
The create method attempts to insert a record to the database and returns an instance of the model if it is successful. If you use create() with invalid values, the insert will fail. I think this is why there is a null instead of an instance of the model, which causes your error:
Call to a member function fill() on null
Instead of using create() You could create the website model without the database insert using
$website = new Website;
$website->fill($request->all());
before you run the validation. If the validation passes, then you can insert to your database with $website->save();, otherwise, it will not try to save, but the model should be available for you to use in your form.

Laravel 4 Form Validation should be unique on update form, but not if current

I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.
However, this continues to return validation error message 'This email has already been taken'.
I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.
HTML
{{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}
Route
Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController#update'));
User Model
'email' => 'unique:users,email,{{{ $id }}}'
Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.
I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.
class User extends Eloquent {
public static $rules = array(
'email' => 'unique:users,email,%1$s'
);
public static function getRules($id = 'NULL') {
$rules = self::$rules;
$rules['email'] = sprintf($rules['email'], $id);
return $rules;
}
}
You can accomplish this with the sometimes function of the validator
Something like:
$validator->sometimes('email', 'unique:users,email', function ($input) {
return $input->email == Input::get('email');
});
See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info

Categories