Reputation: 2430
When someone creates an account in the application I'm building, they have to provide a country.
In order to provide the user with a list of countries to choose from, there is a countries
table with two fields: id
and country_code
. The users
table has a country_id
field.
I would like to use a select box named country
instead of country_id
, but I'm unable to find out how I would accomplish that. Any idea? Of course, validation and stuff still has to work.
Also, is it mandatory to specify the precise field for countries.id
in the validation code? Right now, I have this:
$this->validate($request, [
'name' => 'required',
'country_id' => 'required|exists:countries,id'
]);
As said, the attribute name should be country
instead of country_id
, but since I have specified the Eloquent relationship between the User and the Country model, doing something like 'required|exists:countries'
should do the trick, right?
Upvotes: 1
Views: 838
Reputation: 4168
<select name="country">
<option value="1">US</option>
<option value="2">UK</option>
</select>
And validation
$this->validate($request, [
'country' => 'required|integer|exists:countries,id'
]);
country == name attribute
countries == table name
So it will check the value from selected option(id) with existing id in countries table
If Country exists in table countries with selected ID save user
$user = New User;
$user->country_id = $request->input('country');
$user->save();
Laravel validation doesn't bind your columns in DB with your inputs names
I would also add integer
validation before exists
Upvotes: 2