Thursday, March 9, 2017

New version of Lumen causes route to return Undefined Offset error

Using Lumen 5.4.5.

I recently tried out a dated Lumen tutorial from 2015 (http://loige.co/developing-a-web-application-with-lumen-and-mysql/) with the latest version of Lumen. For the most part, everything from this tutorial which was written for a previous version of Lumen continues to work except for a single route. This route is intended to return a different record from a database table every day of the year. I have previously used this tutorial back in the day and and can confirm that everything at least use to work as intended but some sort of change introduced with the newest version of Lumen seems to treat the syntax differently causing an error.

Here is the route:

    use App\Models\Quote;

/**
 * Display the today quote
 */
$app->get('/', function() use ($app) {

    /*
     * Picks a different quote every day 
     * (for a maximum of 366 quotes)
     *
     *   - $count: the total number of available quotes
     *   - $day: the current day of the year (from 0 to 365)
     *   - $page: the page to look for to retrieve the 
     *            correct record
     */
    $count = Quote::query()->get()->count();
    $day = (int) date('z');
    $page = $day % $count + 1;

    $quotes = Quote::query()->get()->forPage($page, 1)->all();

    if (empty($quotes)) {
        throw new \Illuminate\Database\Eloquent\ModelNotFoundException();
    }

    return view('quote', ['quote' => $quotes[0]]);
});

And here a summary of the error:

ErrorException... Undefined offset: 0

at Application->Laravel\Lumen\Concerns\{closure}(8, 'Undefined offset: 0', '/var/www/motivational/routes/web.php', 44, array('app' => object(Application), 'count' => 3, 'day' => 67, 'page' => 2, 'quotes' => array(object(Quote)))) in web.php line 44

It is specifically complaining about the last line in the route:

return view('quote', ['quote' => $quotes[0]]);

It doesn't seem to like 0 however if I replace that with 1 it works just fine. There are only 3 records in my quotes table with IDs 1 through 3 and today the route is returning ID 2.

Question: What would have caused a previous version of Lumen to accept that last line of code and work without issue while the latest version of Lumen breaks? The only other thing I think to mention is that I was previously doing this tutorial on PHP 5.6 but now I'm on PHP 7.



via sparecycle

Advertisement