tinker.macro
Evaluate Laravel code at build-time, via Laravel Tinker
Installation
Install babel-plugin-macros
(along with tinker.macro
) and add it to your babel config:
npm install --save-dev babel-plugin-macros tinker.macro
.babelrc:
That’s it!
Basic Usage
let isDebug = tinker`config('app.debug')` // ↓ ↓ ↓ ↓ ↓ ↓ ↓ let isDebug = true
If you are executing a single function call you can import the function like this:
let isDebug = // ↓ ↓ ↓ ↓ ↓ ↓ ↓ let isDebug = true
There is also a convenient way to access App\*
class methods and properties:
let article = Article // ↓ ↓ ↓ ↓ ↓ ↓ ↓ let article = id: 7 title: 'Hello, world' body: 'Lorem ipsum dolor sit amet.' // etc.
This is the same as:
let articles = tinker`App\\Article::where('id', 7)->first()`
More Examples
route function
// these are equivalentlet articleRoute1 = let articleRoute2 = tinker`route('article', ['id' => 1])` // ↓ ↓ ↓ ↓ ↓ ↓ ↓ let articleRoute1 = 'http://localhost/article/1'let articleRoute2 = 'http://localhost/article/1'
named routes
Retrieving a list of let routes = tinker` $routes = []; foreach (app()->routes->getRoutes() as $route) { $name = $route->getName(); if ($name !== null) { $uri = $route->uri; $routes[$name] = ($uri === '/' ? '' : '/') . $uri; } } $routes;` // ↓ ↓ ↓ ↓ ↓ ↓ ↓ let routes = home: '/' blog: '/blog' post: '/blog/{slug}'
Re-evaluating on change
If you are using webpack you can ensure that expressions are re-evaluated when updating your Laravel app. Add the loader – tinker.macro/webpack
– to your webpack configuration, like so:
moduleexports = // ... module: rules: test: /\.js$/ exclude: /node_modules/ loader: 'tinker.macro/webpack' // ... // ...