I am creating a coffee shop website because I want to learn Laravel and I like coffee. I have a dashboard where the user can manage his coffee. He can manually select from all kind of coffee. With my approach, I detect 2 Major Problems which is connected to the question.
1. Problem
Let's say the User has added 2 coffees with the id of 1 and 2
id | user_id | selected_coffee | created_at | updated_at
----------------------------------------------------------------
1 | 1 | 1 | xxxxxxxxxx | xxxxxxxxxx
1 | 1 | 2 | xxxxxxxxxx | xxxxxxxxxx
If the User selects in these orders because he can select multiple. * Let's say he select the coffee id 1, 2 and the last one 3.*
Because the code detects that the first id is in the database, it is ignoring the other values.
2. Problem
Let's say the User1 has added 2 coffees with the id of 1 and 2
id | user_id | selected_coffee | created_at | updated_at
----------------------------------------------------------------
1 | 1 | 1 | xxxxxxxxxx | xxxxxxxxxx
1 | 1 | 2 | xxxxxxxxxx | xxxxxxxxxx
The User2 can select the coffee but it is not written in the Database which I need for display visually on the frontend
I know it is not well seen to add 2 Problems but my thought is if we can fix the number 1. The problem then the 2.Problem will disappear.
Here is my code which makes it unique:
public function store(Request $request)
{
app('App\Http\Controllers\ScoreController')->store($request);
$message = ['selected_coffee.unique' => 'Check Coffee ID already exist'];
$this->validate($request,[
'selected_coffee' => 'unique:manage_coffees',
],$message);
if($request->input('checkedDrink') != null){
foreach ($request->input('checkedDrink') as $selected_id) {
$manage_coffee = new ManageCoffee();
$manage_coffee->user_id = \Auth::user()->id;
$manage_coffee->selected_coffee = (int)$selected_id;
$manage_coffee->save();
}
}
return redirect('dashboard/coffee');
}
I found the validator in StackOverflow but it was not well explained. I think I must do a where clause in the ->validate but I don't know where I should put it.
Hopefully, you guys can help me.
Torsten