0

I encountered one issue with laravel 5.3 and maybe you guys have faced similar issue and know what causes it.

I am loading first ten of the activity stream messages (eloquent model activity, which has "read" column which can be 0 or 1 and shows if user has read it) and if there are more then 10 activities, then there is a load more button in the bottom of the page. When load more button is clicked, I am fetching 10 more messages from the back end via ajax call.

Here is the issue:

    $activities = Activity::where( 'to_user_id', Auth::id() )
                          ->latest()
                          ->offset( $offset )
                          ->limit( 10 )
                          ->get();


    Activity::where( 'to_user_id', Auth::id() )
                       ->latest()
                       ->offset( $offset )
                       ->limit( 10 )
                       ->update( [ 'read' => 1 ] );

I run the code above both on first load and on ajax load. First load happens via routes/web.php and it works perfectly and marked initial 10 activities as read..

Ajax calls are handled via ActivityController file but for some reason, the output is correct but "read" column does not get updated. I applied temporary fix:

    foreach($activities as $activity) {
        $activity->read = 1;
        $activity->save();
    }

But I still need to figure out what is wrong with:

    Activity::where( 'to_user_id', Auth::id() )
                       ->latest()
                       ->offset( $offset )
                       ->limit( 10 )
                       ->update( [ 'read' => 1 ] );
Nick Surmanidze
  • 1,671
  • 1
  • 11
  • 20

1 Answers1

0

Because your first WEB request is updating everything after ->get(). It's not possible to do that kind of mass update with Eloquent.

Artur Subotkevič
  • 1,859
  • 1
  • 15
  • 18
  • Hi, thank you for reply. Could you please explain it in little more details. What do you mean by "your first WEB request is updating everything after ->get()" and how does it explain that the same thing works on one place and does not work on the other place? – Nick Surmanidze Dec 14 '16 at 08:16
  • As I can see there is not the same thing. – Artur Subotkevič Dec 14 '16 at 11:11
  • I am using $activities = Activity::where( 'to_user_id', Auth::id() ) ->latest() ->offset( $offset ) ->limit( 10 ) ->get(); Activity::where( 'to_user_id', Auth::id() ) ->latest() ->offset( $offset ) ->limit( 10 ) ->update( [ 'read' => 1 ] ); in both places, for the initial output with offset set to 0 and then for adding older items via ajax so the piece of code is the same. – Nick Surmanidze Dec 14 '16 at 11:39