Skip to content

Misc Features

Max edited this page Jan 2, 2020 · 3 revisions

Eloquent's findOrFail() returns 404 on model not found

Eloquent's findOrFail() functions will result in an http 500 response if the model is not found. Through the RestfulModel class of the boilerplate, it's eloquent builder extends the findOrFail function to catch that exception and re-throw it as an NotFoundHttpException, leading to a more correct http 404 response.

Simple caching on Restful controller

For restful controllers, there is a simple caching feature which you can enable with a boolean property cacheAll on the controller class. When enabled, the get collection endpoint (getAll function)'s output is cached for 24 hours, rather than being queried from the database.

Example;

    /**
     * @var bool Cache the getAll endpoint (for 24h)
     */
    public static $cacheAll = true;

You can also customise the duration of caching with a $cacheExpiresIn property. It should be in seconds as per the PSR cache standard.

    /**
     * @var bool Cache the getAll endpoint (for 24h)
     */
    public static $cacheAll = true;

    /**
     * @var int Cache expiry timeout (2 hours)
     */
    public static $cacheExpiresIn = 1440;

Please note that when cache is enabled, the potentially permissions-related function qualifyCollectionQuery does not get ran on the query (since it wouldn't make sense to cache a single users' viewable collection for everyone), nor can you use pagination.

This functionality is thus useful in situations where you have non-sensitive resources, which do not get changed very often, and the full list of which you will often want to return. Some generic examples of this are as follows:

  • User Roles
  • Localisation resources (ie. languages, currencies, countries, timezones, etc)
  • Fairly static "type-like" resources in your application