Laravel Find In DB Where('week', $week) And Where('user_id', $user_id) To Find Id

- 1 answer

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.


    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.


public function update(Request $request)
        $week = $request->week;
        $challange = Challange::find($request->user_id)->where('week', $week);

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)

// or

$challange = Challange::where([
    'week' => $week, 
    'user_id' => $request->user_id