### Install Multiple Leaf Packages Source: https://leafphp.dev/docs/cli Install several packages at once by listing them after the `leaf install` command. ```bash leaf install auth db illuminate/support ``` -------------------------------- ### Run Vite Development Server Manually (yarn) Source: https://leafphp.dev/docs/frontend/vite Install dependencies and start the Vite development server using yarn. ```bash yarn && yarn dev ``` -------------------------------- ### Run Vite Development Server Manually (npm) Source: https://leafphp.dev/docs/frontend/vite Install dependencies and start the Vite development server using npm. ```bash npm i && npm run dev ``` -------------------------------- ### Build Frontend Setup Source: https://leafphp.dev/docs/cli Use the `leaf view:build` command to prepare your frontend setup for production. ```bash leaf view:build ``` -------------------------------- ### Install Leaf Fetch Package Source: https://leafphp.dev/docs/utils/fetch Install the Fetch package using the Leaf CLI or Composer. ```bash leaf install fetch ``` ```bash composer require leafs/fetch ``` -------------------------------- ### Install BareUI using Composer Source: https://leafphp.dev/docs/frontend/bareui Install the BareUI package using Composer. ```bash composer require leafs/bareui ``` -------------------------------- ### Start Application with Docker Compose Source: https://leafphp.dev/docs/docker Command to build and start the application services defined in the docker-compose.yml file. ```bash docker compose up ``` -------------------------------- ### Run Vite Development Server Manually (pnpm) Source: https://leafphp.dev/docs/frontend/vite Install dependencies and start the Vite development server using pnpm. ```bash pnpm i && pnpm run dev ``` -------------------------------- ### Making a GET Request with Shortcut Source: https://leafphp.dev/docs/utils/fetch Use the `get()` method for making GET requests. The returned data is available in the `data` property. ```php $res = fetch()->get('https://jsonplaceholder.typicode.com/todos/'); // data returned is saved in the $data property just like axios response()->json($res->data); ``` -------------------------------- ### Install Sitemap Package Source: https://leafphp.dev/docs/utils/sitemaps Install the Leaf sitemap package using the Leaf CLI or Composer. ```bash leaf install sitemap ``` ```bash composer require leafs/sitemap ``` -------------------------------- ### Create a New Leaf Project Source: https://leafphp.dev/docs Use the Leaf CLI to create a new project. This command will guide you through the setup process, allowing you to select the type of application to build. ```bash leaf create ``` -------------------------------- ### Welcome Mailer Example Source: https://leafphp.dev/docs/utils/mail/mvc An example of a generated mailer class with a static action method to create and configure an email. ```php create([ 'subject' => 'WelcomeMailer Test', 'body' => 'This is a test mail from action', 'recipientEmail' => $user->email, 'recipientName' => $user->name, // these have been set as defaults in .env file // you can override them here, otherwise, just remove them 'senderName' => _env('MAIL_SENDER_NAME'), 'senderEmail' => _env('MAIL_SENDER_EMAIL'), ]); } } ``` -------------------------------- ### Install Leaf Queue Package Source: https://leafphp.dev/docs/utils/queues Install the leaf/queue package using the Leaf CLI or Composer. ```bash leaf install queue ``` ```bash composer require leafs/queue ``` -------------------------------- ### Install Password Helper via Composer Source: https://leafphp.dev/docs/data/encryption Alternatively, install the password helper using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require leafs/password ``` -------------------------------- ### Install Leaf CLI Source: https://leafphp.dev/docs/migrating Use the Leaf CLI to install Leaf version 4.0-beta. ```bash leaf install leaf@v4.0-beta ``` -------------------------------- ### Create a Basic Leaf PHP App Source: https://leafphp.dev/docs This snippet demonstrates the basic setup for a Leaf PHP application, including routing and JSON response. Ensure you have Composer and PHP installed. ```php get('/', function () { response()->json(['message' => 'Hello World!']); }); app()->run(); ``` -------------------------------- ### Install Leaf Auth via Composer Source: https://leafphp.dev/docs/auth Alternatively, install Leaf Auth using Composer. Ensure you have Composer installed and configured. ```bash composer require leafs/auth ``` -------------------------------- ### Create a GET Route Source: https://leafphp.dev/docs/routing Use the `get()` method to handle HTTP GET requests. It requires a route pattern and a handler function. ```php app()->get('/home', function () { // your code }); ``` -------------------------------- ### Install Latest Aloe and MVC Core via Composer (Beta) Source: https://leafphp.dev/docs/mvc/console Alternatively, install the latest beta versions of Aloe and mvc-core using Composer. ```bash composer require leafs/aloe:v4.0-beta composer require leafs/mvc-core:v4.0-beta ``` -------------------------------- ### Install Eien using Composer Source: https://leafphp.dev/docs/swoole Install the Eien module using Composer. ```bash composer require leafs/eien ``` -------------------------------- ### Install Google OAuth Package Source: https://leafphp.dev/docs/utils/mail Install the league/oauth2-google package using Leaf CLI to handle OAuth connections for Gmail. ```bash leaf install league/oauth2-google ``` -------------------------------- ### Install Leaf FS via Composer Source: https://leafphp.dev/docs/utils/fs Install the Leaf file storage system using Composer. This is the recommended method for most projects. ```bash composer require leafs/fs ``` -------------------------------- ### Install Leaf Form Module Source: https://leafphp.dev/docs/data/validation Install the form module using the Leaf CLI or Composer. ```bash leaf install form ``` ```bash composer require leafs/form ``` -------------------------------- ### Install Leaf Auth Package Source: https://leafphp.dev/docs/auth/permissions Install the Leaf Auth package using either the Leaf CLI or Composer. ```bash leaf install auth ``` ```bash composer require leafs/auth ``` -------------------------------- ### Install Google OAuth Composer Source: https://leafphp.dev/docs/utils/mail Install the league/oauth2-google package using Composer to handle OAuth connections for Gmail. ```bash composer require league/oauth2-google ``` -------------------------------- ### Run Alchemy Setup Command Source: https://leafphp.dev/docs/utils/testing Execute the Alchemy setup command to configure Alchemy for your project. This creates an `alchemy.yml` file and updates `composer.json`. ```bash ./vendor/bin/alchemy install ``` -------------------------------- ### Install Leaf Auth via Leaf CLI Source: https://leafphp.dev/docs/auth Use the Leaf CLI to install the authentication module. This is the recommended method for new projects. ```bash leaf install auth ``` -------------------------------- ### Install Leaf CLI Source: https://leafphp.dev/docs/cli Installs the Leaf CLI globally using Composer. Ensure Composer is installed and its global bin directory is in your system's PATH. ```bash composer global require leafs/cli -W ``` -------------------------------- ### Install BareUI using Leaf CLI Source: https://leafphp.dev/docs/frontend/bareui Install the BareUI package using the Leaf CLI command. ```bash leaf install bareui ``` -------------------------------- ### Handle Cart Purchase (Stripe Example) Source: https://leafphp.dev/docs/utils/billing Example of handling a cart purchase using the billing() helper, which generates a payment link for one-time charges. This example is tailored for Stripe. ```APIDOC ## POST /billing/charge (Stripe Example) ### Description Handles a cart purchase by generating a payment session for Stripe. ### Method POST ### Endpoint /billing/charge ### Parameters #### Request Body - **currency** (string) - Required - The currency to charge the customer (e.g. USD, EUR). - **description** (string) - Optional - A description of the charge. - **metadata** (object) - Optional - An array of metadata to attach to the charge. - **metadata.cart_id** (string) - Required - The ID of the cart. - **metadata.items** (array) - Optional - An array of items to charge the customer, each with a name and amount. - **items** (array) - Optional - Array of Stripe formatted items to charge the customer, eg: `['price_data' => ['currency' => 'usd', 'product_data' => ['name' => 'T-shirt'], 'unit_amount' => 2000], 'quantity' => 1]`. You can use `metadata.items` if you want Leaf to format your data for you. - **customer** (string) - Optional - The customer email to charge. - **urls** (object) - Optional - An array of URLs to redirect the customer to. Accepts `success` and `cancel` keys. If not provided, Leaf will use default URLs. ### Request Example ```php ... public function handleCartPurchase($cartId) { $cart = Cart::find($cartId); $session = billing()->charge([ 'currency' => 'USD', 'description' => 'Purchase of items in cart', 'metadata' => [ 'cart_id' => $cartId, 'items' => $cart->items(), ] ]); $cart->payment_session = $session->id(); $cart->save(); response()->redirect($session->url()); } ``` ### Response #### Success Response (302 Redirect) Redirects the user to the payment session URL. #### Response Example Redirects to a URL provided by the payment gateway. ``` -------------------------------- ### Install Leaf Date Module Source: https://leafphp.dev/docs/utils/date Instructions for installing the Leaf Date module using the Leaf CLI or Composer. ```bash leaf install date ``` ```bash composer require leafs/date ``` -------------------------------- ### Install Specific Package Versions Source: https://leafphp.dev/docs/cli Specify a particular version of a package for installation using the `@` symbol. ```bash leaf install auth@4.0 illuminate/support@9.0.2 ``` -------------------------------- ### Install Leaf DB Module Source: https://leafphp.dev/docs/database Install the Leaf database module using the Leaf CLI or Composer. ```bash leaf install db ``` ```bash composer require leafs/db ``` -------------------------------- ### Install Leaf Session Module Source: https://leafphp.dev/docs/http/session Install the Leaf Session module using either the Leaf CLI or Composer. ```bash leaf install session ``` ```bash composer require leafs/session ``` -------------------------------- ### Get Port Source: https://leafphp.dev/docs/http/request Retrieve the request's port number. Example: 80. ```php request()->getPort(); ``` -------------------------------- ### Verify Leaf CLI Installation Source: https://leafphp.dev/docs/cli Displays the Leaf CLI version to confirm successful installation. ```bash leaf ``` -------------------------------- ### Serve Frontend Development Server Source: https://leafphp.dev/docs/mvc/console Start a local development server for your frontend. ```bash leaf view:serve ``` -------------------------------- ### Root URI Source: https://leafphp.dev/docs/http/request Get the root URI of the Leaf application's installation path. ```APIDOC ## Paths ### Root URI ### Description The root URI is the physical URL path of the directory in which the Leaf application is instantiated and run. ### Method ```php request()->getScriptName(); ``` ``` -------------------------------- ### Install Leaf Composer Package Source: https://leafphp.dev/docs/migrating Install the Leaf PHP package version 4.0-beta using Composer. ```bash composer require leafs/leaf:4.0-beta ``` -------------------------------- ### Connect to MySQL Source: https://leafphp.dev/docs/database Example connection configuration for a MySQL database. ```php db()->connect([ 'host' => '127.0.0.1', 'username' => 'root', 'password' => '', 'dbname' => 'Leaf', ]); ``` -------------------------------- ### Get Content Charset Source: https://leafphp.dev/docs/http/request Fetch the request's content character set. Example: "utf-8". ```php request()->getContentCharset(); ``` -------------------------------- ### Install Leaf Cookie Module Source: https://leafphp.dev/docs/http/cookies Install the cookie module using either the Leaf CLI or Composer. ```bash leaf install cookie ``` ```bash composer require leafs/cookie ``` -------------------------------- ### Install Leaf DevTools Module Source: https://leafphp.dev/docs/routing/error-handling Install the Leaf DevTools module using the Leaf CLI or Composer. ```bash leaf install devtools ``` ```bash composer require leafs/devtools ``` -------------------------------- ### Install Vite Server Component with Composer Source: https://leafphp.dev/docs/frontend/vite Install the server component for Vite using Composer to enable server-side asset loading with PHP. ```bash composer require leafs/vite ``` -------------------------------- ### Get Host with Port Source: https://leafphp.dev/docs/http/request Retrieve the request's host along with its port number. Example: "leafphp.dev:80". ```php request()->getHostWithPort(); ``` -------------------------------- ### Install Leaf Mail Package Source: https://leafphp.dev/docs/utils/mail/mvc Install the Leaf Mail package using either the Leaf CLI or Composer. ```bash leaf install mail ``` ```bash composer require leafs/mail ``` -------------------------------- ### Using S3 or Cloud Storage Source: https://leafphp.dev/docs/utils/fs Integrate with S3-compatible cloud storage services. Configure your credentials in `.env` and install the S3 addon. Use `withBucket()` to specify cloud storage destinations. ```APIDOC ## Using s3 or other cloud storage services Leaf FS now supports using Amazon s3 and other cloud storage services that support the S3 protocol. This allows you to switch from local storage to cloud storage without changing any code. To get started, you need to configure your cloud storage settings in the `.env` file. ### Environment Configuration ```env AWS_ACCESS_KEY_ID=1234567890abcdef1234 AWS_SECRET_ACCESS_KEY=1234567890abcdef1234567890abcdef1234 AWS_DEFAULT_REGION=weur AWS_BUCKET=bucket-name AWS_URL=https://cdn.leafphp.dev AWS_USE_PATH_STYLE_ENDPOINT=false AWS_ENDPOINT=https://something.r2.cloudflarestorage.com ``` ### Installation Install the S3 addon using the Leaf CLI or Composer: #### Leaf CLI ```bash leaf install s3 ``` #### Composer ```bash composer require leafs/s3 ``` ### Usage Now just add `withBucket()` as the destination when creating or uploading files to use the cloud storage. ```php $displayUrl = request()->upload( 'fileInRequest', 'local/path', withBucket('path/in/bucket'), )['url'] ?? null; $videoUrl = storage()->createFile( withBucket("imports/$request/video.mp4"), $this->fetchRemoteVideo($post['videoUrl']), [ 'rename' => true, 'recursive' => true, ] ); ``` We are working on a 100% interchangeable API for local and cloud storage, so you can use `withBucket()` anywhere you would normally use a local path, however, some methods may not be supported yet. We would love to hear your feedback on this feature. ``` -------------------------------- ### Install Vite Server Component with Leaf CLI Source: https://leafphp.dev/docs/frontend/vite Install the server component for Vite using the Leaf CLI to enable server-side asset loading with PHP. ```bash leaf install vite ``` -------------------------------- ### Install Blade with Leaf CLI Source: https://leafphp.dev/docs/frontend/blade Use the Leaf CLI to install the Blade package. This is an alternative to using Composer. ```bash leaf install blade@v4 ``` -------------------------------- ### Get Content Type Source: https://leafphp.dev/docs/http/request Fetch the request's content type, including charset if specified. Example: "application/json;charset=utf-8". ```php request()->getContentType(); ``` -------------------------------- ### Serve a Leaf Project Source: https://leafphp.dev/docs After generating your project, use this command to start the development server and run your Leaf application. ```bash leaf serve ``` -------------------------------- ### Install Eien using Leaf CLI Source: https://leafphp.dev/docs/swoole Install the Eien module using the Leaf Command Line Interface. ```bash leaf install eien ``` -------------------------------- ### Get Media Type Parameters Source: https://leafphp.dev/docs/http/request Fetch the request's media type parameters as an associative array. Example: [charset => "utf-8"]. ```php request()->getMediaTypeParams(); ``` -------------------------------- ### Connect to PostgreSQL Source: https://leafphp.dev/docs/database Example connection configuration for a PostgreSQL database, specifying the port. ```php db()->connect([ 'dbtype' => 'pgsql', 'host' => '127.0.0.1', 'username' => 'root', 'password' => '', 'dbname' => 'Leaf', 'port' => '5432', ]); ``` -------------------------------- ### Install Leaf Packages Source: https://leafphp.dev/docs/cli Use the `leaf install` command to add packages from composer. You can omit the `leafs/` prefix for Leaf modules. ```bash leaf install leafs/auth ``` ```bash leaf install auth ``` -------------------------------- ### Run Distributed Seedling Application (Local Install) Source: https://leafphp.dev/docs/seedling If installed locally within an application, run the Seedling application using PHP and the vendor executable path. ```bash php vendor/bin/mytool greet John --greeting Hi ``` -------------------------------- ### Install Password Helper via Leaf CLI Source: https://leafphp.dev/docs/data/encryption Install the password helper using the Leaf CLI. This is the recommended method for integrating the helper into your project. ```bash leaf install password ``` -------------------------------- ### Install Vite with Leaf CLI Source: https://leafphp.dev/docs/frontend/vite Use this command to install Vite and the leaf-vite module if not using Leaf MVC. ```bash leaf view:install --vite ``` -------------------------------- ### Add shadcn/ui Component Source: https://leafphp.dev/docs/frontend/inertia Install a shadcn/ui component using `pnpm dlx shadcn@latest add` after scaffolding. ```bash pnpm dlx shadcn@latest add switch ``` -------------------------------- ### Get Start of Date Unit Source: https://leafphp.dev/docs/utils/date Use `startOf()` to set the date to the beginning of a specified unit like month or year. Available units include year, month, week, day, hour, minute, and second. ```php tick()->startOf('month'); // => 2024-10-01 00:00:00 tick()->startOf('year'); // => 2024-01-01 00:00:00 ``` -------------------------------- ### Install PayStack Module via Leaf CLI Source: https://leafphp.dev/docs/utils/billing Use the Leaf CLI to install the PayStack module for billing integration. ```bash leaf install paystack # paystack ``` -------------------------------- ### Install Leaf Lingo with Composer Source: https://leafphp.dev/docs/utils/lingo Install the Leaf Lingo package using Composer. This command adds the necessary files to your project. ```bash composer require leafs/lingo ``` -------------------------------- ### Install Stripe Module via Leaf CLI Source: https://leafphp.dev/docs/utils/billing Use the Leaf CLI to install the Stripe module for billing integration. ```bash leaf install stripe # stripe ``` -------------------------------- ### Install Frontend Framework for Inertia Source: https://leafphp.dev/docs/frontend/inertia Use the Leaf MVC console command to install your preferred frontend framework (Vue, React, or Svelte) for Inertia integration. ```bash php leaf view:install --vue ``` ```bash php leaf view:install --react ``` ```bash php leaf view:install --svelte ``` -------------------------------- ### Run Distributed Seedling Application (Global Install) Source: https://leafphp.dev/docs/seedling Once installed globally via Composer, users can run the Seedling application directly by its command name. ```bash mytool greet John --greeting Hi ``` -------------------------------- ### Install Leaf Mail CLI Source: https://leafphp.dev/docs/utils/mail Install Leaf Mail using the Leaf CLI. This is the recommended way to add the package to your project. ```bash leaf install mail ``` -------------------------------- ### Alchemy Configuration File Example Source: https://leafphp.dev/docs/utils/testing An example `alchemy.yml` file showing configurations for application paths, testing engine and paths, linting presets and rules, and GitHub Actions. ```yaml app: - app - src tests: engine: pest parallel: true paths: - tests files: - '*.test.php' coverage: local: false actions: true lint: preset: PSR12 rules: no_unused_imports: true not_operator_with_successor_space: false single_quote: true actions: run: - lint - tests os: - ubuntu-latest php: extensions: json, zip, dom, curl, libxml, mbstring versions: - '8.3' events: - push - pull_request ``` -------------------------------- ### Install Leaf CLI Source: https://leafphp.dev/docs Install the Leaf CLI globally using Composer. This tool is recommended for easier management of Leaf applications. ```bash composer global require leafs/cli -W ``` -------------------------------- ### Get Query Parameters (GET Requests) Source: https://leafphp.dev/docs/http/request Retrieves query parameters from a GET request. You can provide a default value if the parameter is not found. ```APIDOC ## Get Query Parameters (GET Requests) ### Description Retrieves query parameters from a GET request. You can provide a default value if the parameter is not found. ### Method `request()->query(string $key, $defaultValue = null)` ### Parameters - **key** (string) - Required - The key of the query parameter to retrieve. - **defaultValue** (mixed) - Optional - A default value to return if the query parameter does not exist. ### Example ```php $name = request()->query('name', 'John Doe'); ``` ``` -------------------------------- ### Install Vite and Leaf Plugin with npm Source: https://leafphp.dev/docs/frontend/vite Install Vite and the LeafPHP Vite plugin as development dependencies using npm. ```bash npm i -D vite @leafphp/vite-plugin ``` -------------------------------- ### Install CORS Module via Composer Source: https://leafphp.dev/docs/http/cors Alternatively, install the CORS module using Composer. Ensure you have Composer installed and configured for your project. ```bash composer require leafs/cors ``` -------------------------------- ### Install Vite and Leaf Plugin with pnpm Source: https://leafphp.dev/docs/frontend/vite Install Vite and the LeafPHP Vite plugin as development dependencies using pnpm. ```bash pnpm i -D vite @leafphp/vite-plugin ``` -------------------------------- ### Install Leaf Cache Module Source: https://leafphp.dev/docs/utils/cache Install the cache module using the Leaf CLI or Composer. No additional configuration is needed as it supports file-based caching out of the box. ```bash leaf install cache ``` ```bash composer require leafs/cache ``` -------------------------------- ### Install Leaf Redis via Composer Source: https://leafphp.dev/docs/database/redis Install the Leaf Redis module using Composer. This is an alternative installation method for Leaf projects. ```bash composer require leafs/redis ``` -------------------------------- ### Get and Set Date Parts Source: https://leafphp.dev/docs/utils/date Illustrates how to get and set specific parts of a date (e.g., second, year, month) using the same method. ```php tick()->second(30); // set the second to 30 tick()->second(); // get the second ``` ```php tick()->year(2018); // set the year to 2018 tick()->year(); // get the year tick()->month(); // gets current month tick()->month(0); // returns new tick object tick()->day(); // gets day of current week tick()->day(0); // returns new tick object tick()->date(); // gets day of current month tick()->date(1); // returns new tick object tick()->hour(); // gets current hour newDate = tick()->hour(12); // returns new tick object tick()->minute(); // gets current minute tick()->minute(59); // returns new tick object tick()->second(); // gets current second tick()->second(1); // returns new tick object tick()->millisecond(); // gets current millisecond tick()->millisecond(1); // returns new tick object ``` ```php tick()->get('year'); // get the year tick()->set('year', 2018); // set the year to 2018 ``` -------------------------------- ### Get Database Folder Path Source: https://leafphp.dev/docs/mvc/globals Use DatabasePath() to get the path to the database folder. You can pass a subdirectory or filename to get a more specific path. ```php $database = DatabasePath('migrations'); // -> app/database/migrations ``` -------------------------------- ### Install Latest Aloe and MVC Core (Beta) Source: https://leafphp.dev/docs/mvc/console If you encounter missing command errors, update Aloe and mvc-core to the latest beta versions using these commands. ```bash leaf install aloe@v4.0-beta leaf install mvc-core@v4.0-beta ``` -------------------------------- ### Basic Vite Configuration Source: https://leafphp.dev/docs/frontend/vite Example vite.config.js file demonstrating the use of the Leaf Vite plugin with entry points. ```js import { defineConfig } from 'vite'; import leaf from '@leafphp/vite-plugin'; export default defineConfig({ plugins: [ leaf({ input: [ 'path/to/entrypoint.css', 'path/to/entrypoint.js' ], refresh: true }) ] }); ``` -------------------------------- ### Get Views Folder Path Source: https://leafphp.dev/docs/mvc/globals Use ViewsPath() to get the path to the views folder. You can pass a filename to get the path to a specific view file. ```php $view = ViewsPath('index.leaf.php'); // -> app/views/index.leaf.php ``` -------------------------------- ### Get Seeds Folder Path Source: https://leafphp.dev/docs/mvc/globals Use SeedsPath() to get the path to the seeds folder. You can pass a filename to get the path to a specific seed file. ```php $seed = SeedsPath('MainSeed.php'); // -> app/database/seeds/MainSeed.php ``` -------------------------------- ### Get Routes Folder Path Source: https://leafphp.dev/docs/mvc/globals Use RoutesPath() to get the path to the routes folder. Pass a filename to get the path to a specific route file. ```php $routes = RoutesPath('_auth.php'); // -> app/routes/_auth.php ``` -------------------------------- ### Get Models Folder Path Source: https://leafphp.dev/docs/mvc/globals Use ModelsPath() to get the path to the models folder. Pass a filename to get the path to a specific model file. ```php $model = ModelsPath('User.php'); // -> app/models/User.php ``` -------------------------------- ### Get Migrations Folder Path Source: https://leafphp.dev/docs/mvc/globals Use MigrationsPath() to get the path to the migrations folder. You can pass a filename to get the path to a specific migration file. ```php $migration = MigrationsPath('MainMigration.php'); // -> app/database/migrations/MainMigration.php ``` -------------------------------- ### Get Helpers Folder Path Source: https://leafphp.dev/docs/mvc/globals Use HelpersPath() to get the path to the helpers folder. You can pass a filename to get the path to a specific helper file. ```php $helper = HelpersPath('MainHelper.php'); // -> app/helpers/MainHelper.php ``` -------------------------------- ### Start Development Server on Custom Port Source: https://leafphp.dev/docs/mvc/console You can specify a custom port for the development server by using the --port flag. ```bash leaf serve --port=8000 ``` -------------------------------- ### BareUI Template Example Source: https://leafphp.dev/docs/frontend/bareui A basic HTML template file with a .view.php extension, demonstrating BareUI's use of plain PHP syntax. ```html Document Hello World ``` -------------------------------- ### Get Factories Folder Path Source: https://leafphp.dev/docs/mvc/globals Use FactoriesPath() to get the path to the factories folder. Pass a filename to get the path to a specific factory file. ```php $factory = FactoriesPath('UserFactory.php'); // -> app/database/factories/UserFactory.php ``` -------------------------------- ### Get Controllers Folder Path Source: https://leafphp.dev/docs/mvc/globals Use ControllersPath() to get the path to the controllers folder. You can pass a filename to get the path to a specific controller file. ```php $controller = ControllersPath('MainController.php'); // -> app/controllers/MainController.php ``` -------------------------------- ### Generate a Controller with Resource Routes Source: https://leafphp.dev/docs/mvc/console Create a controller and automatically set up resource routes for standard CRUD operations using the --resource flag. ```bash leaf g:controller [name] --resource ``` -------------------------------- ### Get Commands Folder Path Source: https://leafphp.dev/docs/mvc/globals Use CommandsPath() to get the path to the commands folder. Pass a filename to get the path to a specific command file. ```php $command = CommandsPath('MainCommand.php'); // -> app/console/MainCommand.php ``` -------------------------------- ### Generate a Controller with Model or All Files Source: https://leafphp.dev/docs/mvc/console Generate a controller along with a corresponding model file using the --model flag, or generate all related files with the --all flag. ```bash leaf g:controller [name] --model leaf g:controller [name] --all # or -a to generate everything ``` -------------------------------- ### Get Storage Folder Path Source: https://leafphp.dev/docs/mvc/globals Use StoragePath() to get the path to the storage folder. Pass a filename to get the path to a specific file within the storage directory. ```php $storage = StoragePath('MainStorage.php'); // -> storage/MainStorage.php ``` -------------------------------- ### Pre-configured Styled Output Methods Source: https://leafphp.dev/docs/mvc/commands Use convenience methods like success(), error(), warning(), and info() for common styled console messages. ```php $this->success('Operation successful'); $this->error('Operation failed'); $this->warning('This is a warning'); $this->info('This is some information'); ``` -------------------------------- ### Get Public Folder Path Source: https://leafphp.dev/docs/mvc/globals Use PublicPath() to get the path to the public folder. You can pass a filename to get the path to a specific file within the public directory. ```php $public = PublicPath('index.php'); // -> public/index.php ``` -------------------------------- ### Publish All Leaf MVC Config Files Source: https://leafphp.dev/docs/mvc Run this command to create the 'config' directory and copy all default configuration files. ```bash leaf config:publish ``` -------------------------------- ### Get Lib Folder Path Source: https://leafphp.dev/docs/mvc/globals Use LibPath() to get the path to the lib folder. Pass a filename to get the path to a specific file within the lib directory. ```php $lib = LibPath('MainLib.php'); // -> lib/MainLib.php ``` -------------------------------- ### Run the Router Source: https://leafphp.dev/docs/routing After defining routes, call the `run()` method to start the router and listen for incoming requests. ```php app()->run(); ``` -------------------------------- ### Install Leaf Redis via Leaf CLI Source: https://leafphp.dev/docs/database/redis Install the Leaf Redis module using the Leaf CLI. This command is used for quick installation within a Leaf project. ```bash leaf install redis ``` -------------------------------- ### Set Up Mail Configuration Source: https://leafphp.dev/docs/mvc/console Run this command to install the Leaf Mail package and configure the necessary settings for sending emails from your application. ```bash leaf mail:setup ``` -------------------------------- ### Start a Queue Worker Source: https://leafphp.dev/docs/utils/queues Manually start a worker process to process jobs from the queue using the queue:work command. Leaf automatically starts a worker when using 'leaf serve'. ```bash leaf queue:work ``` -------------------------------- ### Serve Leaf Application from Different Directory Source: https://leafphp.dev/docs/cli Starts a development server for a Leaf application located in a different directory by providing the path as an argument. ```bash leaf serve /path/to/your/app ``` -------------------------------- ### Upload Files to Cloud Storage Source: https://leafphp.dev/docs/utils/fs Use the withBucket() helper with request()->upload() or storage()->createFile() to direct files to cloud storage. This allows seamless switching between local and cloud storage. ```php $displayUrl = request()->upload( 'fileInRequest', 'local/path', withBucket('path/in/bucket'), )['url'] ?? null; $videoUrl = storage()->createFile( withBucket("imports/$request/video.mp4"), $this->fetchRemoteVideo($post['videoUrl']), [ 'rename' => true, 'recursive' => true, ] ); ``` -------------------------------- ### Serve Leaf Application Source: https://leafphp.dev/docs/cli Starts a development server for your Leaf application. By default, it runs on `localhost:5500`. ```bash cd my-app leaf serve ``` -------------------------------- ### Indexed Array Examples Source: https://leafphp.dev/docs/data/validation Examples of indexed arrays containing strings and numbers. ```php ['one', 'two', 'three'] // Indexed array of strings [1, 2, 3] // Indexed array of numbers ``` -------------------------------- ### Serve File Downloads with download() Source: https://leafphp.dev/docs/http/response Use the `download()` method to send a file to the user for download. Provide the file path, an optional filename, and an optional status code (defaults to 200). ```php response()->download('path/to/file.pdf'); response()->download('path/to/file.pdf', 'new-filename.pdf', 200); ``` ```php $app->response()->download('path/to/file.pdf'); $app->response()->download('path/to/file.pdf', 'new-filename.pdf', 200); ``` -------------------------------- ### Get Assets Folder Path Source: https://leafphp.dev/docs/mvc/globals Use assets() to get the path to the assets folder. Pass a filename to get the path to a specific file within the assets directory. The default path can be configured in config/paths.php. ```php $asset = assets('css/main.css'); // -> public/assets/css/main.css ``` ```php 'assets' => 'public/assets' ``` -------------------------------- ### Connect to SQLite Source: https://leafphp.dev/docs/database Example connection configuration for an SQLite database, specifying the database file name. ```php db()->connect([ 'dbtype' => 'sqlite', 'dbname' => 'db.sqlite', ]); ``` -------------------------------- ### Configure Library Autoloading Source: https://leafphp.dev/docs/mvc/libraries Run this command to create a 'lib' folder and enable autoloading for libraries placed within it. ```bash leaf config:lib ``` -------------------------------- ### Install Blade with Composer Source: https://leafphp.dev/docs/frontend/blade Install the Blade package using Composer for your Leaf PHP project. ```bash composer require leafs/blade:v4 ``` -------------------------------- ### Configure Vite Aliases Source: https://leafphp.dev/docs/frontend/vite Example vite.config.js showing how to set up path aliases for assets using the resolve.alias option. ```js import { defineConfig } from 'vite'; import leaf from '@leafphp/vite-plugin'; export default defineConfig({ plugins: [ leaf({ input: [ 'path/to/entrypoint.css', 'path/to/entrypoint.js' ], refresh: true }) ], resolve: { alias: { '@': '/path/to/folder', } } }); ``` -------------------------------- ### Connect to a Database Source: https://leafphp.dev/docs/database Establish a connection to a database using the `db()->connect()` method with an array of connection details. Leaf DB defers actual connection until a query is run. ```php db()->connect([ 'dbtype' => '...', 'charset' => '...', 'port' => '...', 'unixSocket' => '...', 'host' => '...', 'username' => '...', 'password' => '...', 'dbname' => '...', ]); ``` -------------------------------- ### Handle Cart Purchase (PayStack Example) Source: https://leafphp.dev/docs/utils/billing Example of handling a cart purchase using the billing() helper, specifically configured for PayStack. This includes amount, currency, and a callback URL. ```APIDOC ## POST /billing/charge (PayStack Example) ### Description Handles a cart purchase using the billing() helper, configured for PayStack. This example includes specific parameters for PayStack like amount and a callback URL. ### Method POST ### Endpoint /billing/charge ### Parameters #### Request Body - **amount** (integer) - Required - The total amount of the transaction in the lowest currency unit. - **currency** (string) - Required - The currency to charge the customer (e.g. GHS, NGN). - **description** (string) - Optional - A description of the charge. - **customer** (string) - Optional - The customer email to charge. - **url** (string) - Optional - The URL to redirect the customer to on payment completion or cancellation. If not provided, Leaf will use the default URL. - **metadata** (object) - Optional - An array of metadata to attach to the charge. - **metadata.cart_id** (string) - Required - The ID of the cart. - **metadata.customer_id** (string) - Required - The ID of the customer. - **_paystack** (object) - Optional - Any other PayStack specific parameters you want to pass to the PayStack API. Check the PayStack documentation for more information. ### Request Example ```php ... public function handleCartPurchase($cartId) { $cart = Cart::find($cartId); $session = billing()->charge([ 'amount' => $cartTotal * 100, 'currency' => 'NGN', 'description' => 'Purchase of items in cart', 'customer' => $customer->email, 'url' => 'https://example.com/billing/callback', // only for paystack 'metadata' => [ 'cart_id' => $cart->id, 'customer_id' => $customer->id, ] ]); $cart->payment_session = $session->id(); $cart->save(); response()->redirect($session->url()); } ``` ### Response #### Success Response (302 Redirect) Redirects the user to the payment session URL. #### Response Example Redirects to a URL provided by the payment gateway. ``` -------------------------------- ### Get Current Timestamp and Format Source: https://leafphp.dev/docs/utils/date Demonstrates how to get the current timestamp and format it using the tick() function. ```php tick()->now(); // get the current timestamp tick()->format('YYYY-MM-DD'); // format the current timestamp ``` ```php tick() ->startOf('month') ->add(1, 'day') ->set('year', 2018) ->format('YYYY-MM-DD HH:mm:ss'); ``` -------------------------------- ### Create Folders Source: https://leafphp.dev/docs/utils/fs Use storage()->createFolder() to create directories. It accepts a path and optional configuration for recursive creation or renaming if the folder exists. ```php storage()->createFolder('path/to/folder'); storage()->createFolder('path/to/folder', [ 'recursive' => true ]); ``` ```php $created = storage()->createFolder('path/to/folder', [ 'rename' => true ]); if ($created) { echo 'Folder created successfully'; } else { $errors = storage()->errors(); } ``` -------------------------------- ### Making a GET Request and Accessing Data Source: https://leafphp.dev/docs/utils/fetch Perform a GET request and immediately access its JSON data. ```php $response = fetch([ 'method' => 'GET', 'url' => 'https://jsonplaceholder.typicode.com/todos/1' ]); response()->json($response->data); ```