Helper functions and Globals
Rhapsody includes some helper functions and globally accessible variables to help smooth out your workflow.
Functions
These PHP functions are available everywhere in your application: controllers, models, middleware, and so on.
redirect()
Use this function in your controllers whenever you need to redirect a request. It takes two arguments:
$url and $redirectCode (optional). The redirect code defaults to 302 if it isn't set.
// In your controller file
public function submitForm() {
//--- if form posts successfully, redirect user to some other page ---//
return redirect('/dashboard');
}
public function anotherExample() {
//--- We want to set something other than 302 ---//
$redirectCode = 308;
return redirect('/dashboard', $redirectCode);
}
A few things to keep in mind:
-
Return the result.
redirect()returns aRedirectResponseobject. The redirect is sent when that response is returned from your controller. -
Subdirectory installs are handled for you. For paths like
/dashboard, Rhapsody prepends theAPP_BASE_URLvalue from your.envfile automatically. Never include it yourself. The same code works whether your site lives at the domain root or in a subdirectory. -
Absolute URLs are left alone.
redirect('https://example.com/thanks')is sent exactly as written. -
The status code must be a 3xx code. Anything outside 300–399 throws an
InvalidArgumentException. The most common choices are301(permanent),302(temporary, the default),303(see other, ideal after a form POST),307(temporary, keeps the request method) and308(permanent, keeps the request method). -
Flash a message with the redirect by chaining
with(). See flash below for reading it in your templates.
return redirect('/cart/out-of-stock')->with('error', 'This item is out of stock.');
Security note: if a redirect target ever comes from user input (a ?redirect= query parameter, for example), validate it before passing it to redirect(). Absolute URLs are passed through untouched, so an unchecked value can send visitors to another site.
dump(), d() and dd()
Debugging helpers that accept any number of variables.
dump(...$vars): outputs each variable.d(...$vars): dumps each variable and lets the script keep running.dd(...$vars): dumps each variable, then stops script execution ("dump and die").
If the Symfony VarDumper component is installed, the output is the familiar collapsible, colorized dump. Otherwise Rhapsody falls
back to PHP's built-in var_dump().
$user = $this->users->find($id);
d($user); // inspect it, then carry on
dd($user, $request->all()); // inspect both, then halt
Note Remove these calls before deploying. They print straight to the page and dd() will halt the request.
Twig Globals
The following variables are registered on the Twig environment, so every template can use them without you passing them from a controller.
app_url
The value of APP_URL from your .env file: the scheme and host only, such as http://localhost.
Empty string if it isn't set.
base_url
APP_URL and APP_BASE_URL joined together, giving the full URL of your installation root. On a root install
this is the same as app_url. In a subdirectory install (APP_BASE_URL="/rhapsody") it becomes
http://localhost/rhapsody. Use it for links and assets so your templates work on either kind of install.
Log in
Note Keep both APP_URL and APP_BASE_URL defined in your .env file. Leave
APP_BASE_URL blank (APP_BASE_URL="") for a root install, but don't delete the line.
app_env
The current environment, from APP_ENV: development or production (the default if unset).
Handy for showing things only while developing.
{% if app_env == 'development' %}
{% endif %}
app_theme and APP_THEME
The name of the active theme, from APP_THEME in your .env file. It matches the folder name inside
views/themes/. Both names hold the same value.
auth
Information about the current visitor's login state, with two properties:
auth.check:trueif a user is logged in, otherwisefalse.auth.user: the logged-in user's record, ornullfor guests.
{% if auth.check %}
Welcome back, {{ auth.user.name }}!
Log out
{% else %}
Log in
{% endif %}
auth is lazy: the user is only loaded from the database when you actually use auth.user, so pages
that only call auth.check cost nothing extra. The fields available on auth.user depend on what your
User model returns. Each use of auth.user looks the user up again, so if you need it several times on
one page, store it once:
{% set user = auth.user %}
{{ user.name }} · {{ user.email }}
flash
Gives templates access to one-time flash messages, such as those set with redirect()->with(). Read a message by
the key you used when setting it.
// Controller
return redirect('/dashboard')->with('success', 'Your profile was updated.');
{# Template #}
{% if flash.success %}
{{ flash.success }}
{% endif %}
Like auth, flash messages are read on demand, so there is no cost when a page doesn't use them.
Twig Functions
These template functions are registered alongside the globals.
csrf_field()
Outputs a hidden input containing the current session's CSRF token (named _token). Put it inside every form that
submits via POST.
image_url()
This Twig function is used in conjunction with the image manipulation library. It builds URLs and links to images, and provides resizing, signed URLs, caching and other utilities. This is the recommended way to serve your graphic files, but requires a couple more steps than just pasting a link.
If you don't need any of the advanced features of the image library and just want to drop in a quick link, either use the Path helper in your controllers, or {{ base_url }} in your view files directly to link to your images.
// In your controller. Make sure to import Rhapsody\Core\Helpers\Path
$imgPath = Path::public('images/icons');
$img = 'user.jpg';
// Builds the full image url that you can then pass to your view
$imgUrl = $imgPath . $img;
// Or, link to the same image directly in your view file
<img src="{{ base_url }}/public/images/icons/user.jpg">
vite_assets(entry)
Outputs the correct <script>/<link> tags for a Vite entry point. The HTML is printed as-is, without
escaping. Pass the entry point name defined in your Vite configuration.
{{ vite_assets('resources/js/app.jsx') }}