Skip to content

Instantly share code, notes, and snippets.

@kharysharpe
Created April 5, 2016 19:14
Show Gist options
  • Save kharysharpe/0ebadbd38cf626989ab7682b6d2913c9 to your computer and use it in GitHub Desktop.
Save kharysharpe/0ebadbd38cf626989ab7682b6d2913c9 to your computer and use it in GitHub Desktop.
Laravel Fetch

Illuminate\Database\Eloquent\Builder


    /**
     * Fetch the row from the result set
     *
     * @param  callable  $callback
     * @return bool
     */
    public function fetch(callable $callback)
    {
        $builder = $this->applyScopes();

        $statement = $this->query->fetch();


        while ($row = $statement->fetch()) {
            // On each result set, we will pass them to the callback and then let the
            // developer take care of everything within the callback, which allows us to
            // keep the memory low for spinning through large result sets for working.
            if (call_user_func($callback, $row) === false) {
                return false;
            }

        }

        return true;
    }


Illuminate\Database\Query\Builder


    /**
     * Execute the query as a "select" statement.
     *
     * @return mixed
     */
    public function fetch()
    {
        $results =  $this->connection->fetch($this->toSql(), $this->getBindings(), ! $this->useWritePdo);

        return $results;
    } 


Illuminate\Database\Connection


    public function fetch($query, $bindings = [], $useReadPdo = true)
    {
        return $this->run($query, $bindings, function ($me, $query, $bindings) use ($useReadPdo) {
            if ($me->pretending()) {
                return [];
            }

            // For select statements, we'll simply execute the query and return an array
            // of the database result set. Each element in the array will be a single
            // row from the database table, and will either be an array or objects.
            $statement = $this->getPdoForSelect($useReadPdo)->prepare($query);

            $statement->execute($me->prepareBindings($bindings));

            return $statement;
        });
    }


Usage:


Flight::fetch(function ($result) {
    
    // Do something with $result

});


@kharysharpe
Copy link
Author

in Laravel 5.3+ as cursor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment