i am creating an app, where users can start a challange to see who loses the most weight.
There is 1 challange table, with an id, user_id(fk), weight and week. To display them in the front end per week i made a new array.
UserController:
public function index()
{
$users = User::all();
// get all challanges descending
$challanges = Challange::orderBy('week', 'DESC')->get();
// make an array for every [week] that has an array with ['user' => 'weight'] in user_id order
$weightArray = array();
// how long is the list depending on amount of weeks
$startweek = 1;
$endweek = Challange::max('week');
// go through every week
for ($i = $startweek; $i <= $endweek; $i++) {
// get weight foreach user and if no value set 0
foreach ($users as $user) {
// get challange values per week
$challenge = $user->challanges()->where('week', '=', $i)->get();
// if there is a challange
if (count($challenge) > 0) {
// set a weight value for that user *!!FIX make weigt alue unique!!*
$weightArray[$i][$user->id] = $challenge[0]->weight;
}
else {
// set 0 if no weight isset
$weightArray[$i][$user->id] = 0;
}
}
}
return view('dashboard', compact('users', 'weightArray'));
}
When a user is logged in and presses update there is a form that gives hidden input Auth::user()->id and week. The weight the user has to input himself. This returns a request, but now i don't know how i can match the week and user_id, to find the id where the weight needs to be updated.
ChallangeController:
public function update(Request $request)
{
$week = $request->week;
$challange = Challange::find($request->user_id)->where('week', $week);
dd($challange);
}
This returns: Error Call to a member function where() on null
Should i add the id in the array upfront? Or do i where('user_id', $user_id) and do another where on an array that returns?
I don't know what to do. Can somebody please help?
Wrong order. You should :
$challange = Challange::where('week', $week)
->where('user_id', $request->user_id)
->first();
// or
$challange = Challange::where([
'week' => $week,
'user_id' => $request->user_id
])->first();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.