简体   繁体   中英

Best way to paginate an array of data in laravel and use infinite scroll with vuejs

Please someone should help me out, i have and array of data (the array contains a logged in users posts and the posts of the logged-in user friends : that is if i log in, it will fetch my posts and my friends posts), this array fetches all post so if i have 100 friends and each of my friend have 30 posts, i will be fetching 300 posts, i want to paginate the fetched data and fetch 5 posts from the array, the fetch more as the user scrolls down the page am using laravel and vuejs to display the data, pls whats the best way to implement this, check my already written code

public function feeds()
{
    $friends = Auth::user()->friends();

    $feed = array();

    foreach ($friends as $friend):

        foreach ($friend->posts as $post):

            array_push($feed, $post);

        endforeach;

    endforeach;


    foreach (Auth::user()->posts as $post):

        array_push($feed, $post);

    endforeach;

    usort($feed, function($p1, $p2){
        return $p1->id < $p2->id;
    });

    return $feed;
}

The vuejs

get_feed()
{
    this.loading = true;
    axios.get('/feed').then((response) => {
        this.loading = true;
        response.data.forEach((post) => {
        this.$store.commit('add_post', post)
            this.loading = false;
        })
    })
} 
computed: {
    posts() {
        return this.$store.getters.all_posts
    },
}

here a much faster version to retreive the posts.

public function feeds(){
    $userdIds = Auth::user()->friends()->pluck('id')->toArray();
    $userIds[] = Auth::id();

    $feed = Post::whereIn('user_id', $userIds)->orderBy('id', 'desc')->paginate(10);
    return $feed; 
}

Thanks N69S i finally came up this

    public function feeds(){
    $userIds = Auth::user()->friends_id();
    array_push($userIds, Auth::id());

    $feed = Posts::whereIn('user_id', $userIds)->orderBy('id', 'desc')->paginate(5);
    return $feed;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM