[laravel] Laravel Eloquent limit and offset

This is mine

    $art = Article::where('id',$article)->firstOrFail();
    $products = $art->products;

I just wanna take a limit 'product' This is wrong way

   $products = $art->products->offset($offset*$limit)->take($limit)->get();

Please give me a hand!

Thanks!

This question is related to laravel eloquent limit offset

The answer is


skip = OFFSET
$products = $art->products->skip(0)->take(10)->get(); //get first 10 rows
$products = $art->products->skip(10)->take(10)->get(); //get next 10 rows

From laravel doc 5.2 https://laravel.com/docs/5.2/queries#ordering-grouping-limit-and-offset

skip / take

To limit the number of results returned from the query, or to skip a given number of results in the query (OFFSET), you may use the skip and take methods:

$users = DB::table('users')->skip(10)->take(5)->get();

In laravel 5.3 you can write (https://laravel.com/docs/5.3/queries#ordering-grouping-limit-and-offset)

$products = $art->products->offset(0)->limit(10)->get(); 

Laravel 8 (This is worked for the version 7.16)

$art->products->skip($offset*$limit)->take($limit)->all();

https://laravel.com/docs/8.x/collections#method-take


Maybe this

$products = $art->products->take($limit)->skip($offset)->get();


You can use skip and take functions as below:

$products = $art->products->skip($offset*$limit)->take($limit)->get();

// skip should be passed param as integer value to skip the records and starting index

// take gets an integer value to get the no. of records after starting index defined by skip

EDIT

Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

REf : https://laravel.com/docs/5.1/collections#method-forpage

e.g

$products = $art->products->forPage($page,$limit);

Quick:

Laravel has a fast pagination method, paginate, which only needs to pass in the number of data displayed per page.


//use the paginate
Book::orderBy('updated_at', 'desc')->paginate(8);

how to customize paging:

you can use these method: offset,limit ,skip,take

  • offset,limit : where does the offset setting start, limiting the amount of data to be queried

  • skip,take: skip skips a few pieces of data and takes a lot of data

for example:


Model::offset(0)->limit(10)->get();

Model::skip(3)->take(3)->get();


//i use it in my project, work fine ~

class BookController extends Controller
{
    public function getList(Request $request) {

        $page = $request->has('page') ? $request->get('page') : 1;
        $limit = $request->has('limit') ? $request->get('limit') : 10;

        $books = Book::where('status', 0)->limit($limit)->offset(($page - 1) * $limit)->get()->toArray();

        return $this->getResponse($books, count($books));
    }
}



$collection = collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);

$chunk = $collection->forPage(2, 3);

$chunk->all();

Please try like this,

return Article::where('id',$article)->with(['products'=>function($products, $offset, $limit) {
    return $products->offset($offset*$limit)->limit($limit);
}])

Try this sample code:

$art = Article::where('id',$article)->firstOrFail();

$products = $art->products->take($limit);

laravel have own function skip for offset and take for limit. just like below example of laravel query :-

Article::where([['user_id','=',auth()->user()->id]])
                ->where([['title','LIKE',"%".$text_val."%"]])
                ->orderBy('id','DESC')
                ->skip(0)
                ->take(2)
                ->get();

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to eloquent

Eloquent: find() and where() usage laravel How to select specific columns in laravel eloquent Laravel Eloquent where field is X or null Laravel Eloquent limit and offset laravel collection to array Eloquent get only one column as an array Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0 Laravel 5.2 - pluck() method returns array Eloquent ORM laravel 5 Get Array of ids eloquent laravel: How to get a row count from a ->get()

Examples related to limit

Laravel Eloquent limit and offset How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu? Pagination using MySQL LIMIT, OFFSET How to fix the "508 Resource Limit is reached" error in WordPress? How to limit the number of dropzone.js files uploaded? Google drive limit number of download How can I list (ls) the 5 last modified files in a directory? Limiting Python input strings to certain characters and lengths MySQL JOIN with LIMIT 1 on joined table MySQL - UPDATE query with LIMIT

Examples related to offset

Laravel Eloquent limit and offset Get div's offsetTop positions in React Bootstrap 3: Offset isn't working? How to fix Warning Illegal string offset in PHP Pagination using MySQL LIMIT, OFFSET How do I get the offset().top value of an element without using jQuery? Get position/offset of element relative to a parent container? offsetting an html anchor to adjust for fixed header Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge? Can you control how an SVG's stroke-width is drawn?