Laravel: The magic of “build()”

Just an easy snippet you should take into consideration when building something.

Image for post
Image for post
<?php

namespace App;

use Illuminate\Contracts\Cache\Store as Cache;

class SaveSomethingTemporarily
{

/**
* The Cache Store
*
*
@var Cache
*/
private $cache;

/**
* SaveSomethingTemporarily constructor.
*
*
@param Cache $cache
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}

/**
* Saves a String for 10 minutes
*
*
@param string $string
*/
public function saveStringForTenMinutes(string $string)
{
$this->cache->put('scratch', $string, 10);
}

}
<?php

namespace App\Http\Controllers;

use App\SaveSomethingTemporarily;

class SaveController extends Controller
{

/**
* Saves a String for 10 minutes
*
*
@param string $string
*
@throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function saveString(string $string)
{
app()->build(SaveSomethingTemporarily::class)
->saveStringForTenMinutes($string);
}

}

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store