Laravel Collective - Model binding issue for non eloquent table names - laravel

I have a User model that has to have a table named admin_users, which is already stipulated in the model (protected $table = 'admin_users';)
I am using Laravel Collective form as follows:
{!! Form::model($user, ['route' => ['users.update', $user->id], 'method' => 'put']) !!}
My validation as follows:
$rules = array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'email|max:255|unique:users',
'country_id' => 'required|numeric',
'user_status' => 'required'
);
The only reason I am using Laravel Collective FORM::model for the ease of getting the request input back when validation fails:
(return redirect()->back()->withErrors($validator)->withInput($request->all())
On validation success though I am getting:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'crm.users' doesn't exist (SQL: select count(*) as aggregate from `users` where `email` = jocelyn33#example.com)
The weird thing is that it's not taking the table from User class table.
My question is if there is a way to have FORM::model get admin_users table name rather than users, and if I decide to let go of FORM::model and use FORM::open, would I still be able to get back request inputs of a failed validation?

Your validation rules are defining what table to use for a unique check:
'email' => 'email|max:255|unique:users',
unique:users is telling the unique rule to use the users table.
unique:table,column,except,idColumn -
Laravel Docs 5.6 - Validation - Unique Rule

Related

Validation check if requested value exists in another table Laravel 9

Hello i am trying to make a validation that checks the inserted values if they exist or not in other tables. This is the code i have done now:
$request->validate([
'order_number' => 'required',
'client_id' => 'required,exists:clients',
'description' => 'required',
]);
These values are inserted in a table called order but the client_id is taken from another table called clients and i want to verify if the value of client_id exists in the row id of the table clients
Please check here
Laravel Validation
As mentioned in laravel document you need to specify a column name, because if you don't, it will use the key in the request for the column name, so in your example, it will be the clients table and client_id column but you need to specify the column name in exists rule, it will be something like this:
$request->validate([
'order_number' => 'required',
'client_id' => 'required|exists:clients,id',
'description' => 'required',
]);
Also, you used the wrong syntax for separating rules, after required you need to use a pipe(|) to separate your rules and use multiple validations.

Having multiple columns (foreign keys) of the same n-n relation in Backpackforlaravel

I'm struggling with the following situation:
My entities Session & Registration are related with a many-to-many (n-n) relationship. In Registration, I have two foreign keys, player_id and hotel_id.
In the Session CrudController, I want to display the related name(s) of the Player(s) and Hotel(s).
For Player, it worked like this:
CRUD::addColumn([
// any type of relationship
'name' => 'registrations', // name of relationship method in the model
'type' => 'relationship',
'label' => 'Spieler', // Table column heading
// OPTIONAL
'entity' => 'registrations', // the method that defines the relationship in your Model
'attribute' => 'player.full_name', // foreign key attribute that is shown to user
'model' => App\Models\Registration::class, // foreign key model
]);
So I've continued to add the Hotel like this:
CRUD::addColumn([
// any type of relationship
'name' => 'registrations', // name of relationship method in the model
'type' => 'relationship',
'label' => 'Hotel', // Table column heading
// OPTIONAL
'entity' => 'registrations', // the method that defines the relationship in your Model
'attribute' => 'hotel.name', // foreign key attribute that is shown to user
'model' => App\Models\Registration::class, // foreign key model
]);
But unfortunately it doesn't work - I don't get an error message, it just keeps showing only the Player column. I think the reason for this is the same value in 'name' - because after commenting the 'name' value in Player, the Hotel information was visible. But I have no idea how to avoid it.
Currently I'm not sure if it's a bug or if I'm doing anything wrong. Would appreciate any kind of support - thanks in advance!
thank you #tabacitu, that works!
I've added
'key' => 'hotel'
and it showed up in the table.

How to use Rule:unique with array of values compared to another column in laravel?

i have a request for array of values and i validate it with the following code
$request->validate([
'doctor_id.*' => ['required'],
'doctor_id' => [Rule::unique('project_orders')->where(function ($query) use ($student) {
$query->where('student_id', $student->id);
})],
]);
but the unique validation doesn't work and the data was inserted to the table with duplication
i want the doctor_id field to be unique with the student_id column, what should be the correct rule?
any help please ?
First you need to do validation on database level, so you will add in your migration
$table->unique(['doctor_id', 'student_id']);
This will make sure that there will be no duplication for same doctor_id and student_id values
Then in your validation layer you will add
$request->validate([
'doctor_id.*' => 'unique:project_orders,doctor_id,NULL,id,student_id,'.$student->id,
]);
You can do the validation like this
$request->validate([
'doctor_id.*' => [ Rule::unique('project_orders', 'doctor_id')->where('student_id', $student->id) ]
]);

Adding custom (guarded) field to Laravel 5.3 Auth

I am trying to add a custom field 'role' to Laravel 5.3 User Auth. The role will determine whether the user is admin amongst other roles and so because the Auth scaffolding uses mass assignable attributes, there is a vulnerability.
Therefore I have changed my User model to:
protected $guarded = [
'role'
];
RegisterController I have added my custom fields (a default user will have the role = customer);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'facebook_id' => $data['facebook_id'],
'linkedin_id' => $data['linkedin_id'],
'avatar' => $data['avatar'],
'token' => $data['token'],
'role' => 'customer',
I am getting this error message:
SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default >value (SQL: insert into users (name, email, password, >facebook_id, linkedin_id, avatar, token, updated_at, >created_at) values (name, name#domain.co.uk, hashed password, , , , , >2017-01-20 17:21:16, 2017-01-20 17:21:16))
Can't for the life of me figure it out.
I was thinking that maybe I don't use the mass assignable input, but I have a feeling that may mess up the rest of the Auth scaffold.
Thanks for any help
An easy way to set the default role is to actually define it in the model
class User extends Model
{
protected $attributes = [
'role' => 'customer',
];
protected $guarded = [
'role'
];
//...
Now when you use the create method and don't pass the the 'role' attribute, the insert will use the value 'customer'
In your migration for the users table where you add the role field, you either need to set the field as nullable, or give it a default value, so that when you mass assign without it, the database knows how to deal with that field.
Schema::table('users' function(Blueprint $table){
$table->string('role')->default('customer');
});
or
Schema::table('users' function(Blueprint $table){
$table->string('role')->nullable();
});
if your code can deal with a null role value.

cakephp saveAssociated and validation foreign_key fails

I have two models that we're going to name Model and RelatedModel. Model has many RelatedModel. So if I add foreign key validation on validation array like:
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'required' => true,
'message' => 'The id of relatedmodel should be a number'
)
)
After I create a add() function to save new registers and in this function I use saveAssociated with validation true, this one fails throwing an error 'The id of relatedmodel should be a number'.
I'm debugging the code and saveAssociated checks validation of both models at the same time and before save Model.
Is this an issue?
I think what this function should do is to validate Model, save it, add foreignKey of RelatedModel and then validate it before save.
I came into this issue only recently. It's not an issue, saveAssociated() is designed to work this way unfortunately.
What you can do is alter the required => true on the fly using the model validator. Check out the book for more information.
http://book.cakephp.org/2.0/en/models/data-validation.html#dynamically-change-validation-rules
This is working as would be expected with your given rule. required in Cake means it expects the value of foreignKey to be set in the save data prior to saving. All the validation will happen before Cake saves the data (and therefore before foreignKey is generated).
You shouldn't need to validate that it is numeric if you are allowing Cake to generate this for you behind the scenes. If you want to check that it is being passed in the data for an UPDATE you could modify the required to be only for an update like this:-
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'required' => 'update',
'message' => 'The id of relatedmodel should be a number'
)
)
Personally I wouldn't bother validating foreign keys unless a user is setting them rather than Cake.
Update:
To validate the foreignKey if it exists in a form submission you can drop the required option from the validation rule:-
public $validate = array(
'foreignKey' => array(
'rule' => 'numeric',
'message' => 'The id of relatedmodel should be a number'
)
);
This will allow you to pass data where the foreignKey is not present without throwing a validation error whilst validating it if it is.

Resources