### PHP Base Class Setup Method
Source: https://ashallendesign.co.uk/blog/the-difference-between-self-static-and-parent-in-php
Demonstrates a basic setup method in a base class. This is a foundational example for inheritance.
```php
class BaseTestCase
{
public function setUp(): void
{
echo 'Run base test case set up here...';
}
}
(new BaseTestCase())->setUp();
// Output is: "Run base test case set up here...';
```
--------------------------------
### Instantiating a GitHub Driver
Source: https://ashallendesign.co.uk/blog/php-match-expression
This is an example of how to use the RepositoryManager class to get a driver instance for GitHub.
```php
$githubDriver = new RepositoryManager()->driver('github');
```
--------------------------------
### Start Laravel Development Server
Source: https://ashallendesign.co.uk/blog/laravel-implementing-feature-flags
Start the Laravel development server to view the application in the browser.
```bash
php artisan serve
```
--------------------------------
### Install spatie/data-transfer-object Package
Source: https://ashallendesign.co.uk/blog/cleaning-up-laravel-controllers
Install the data transfer object package using Composer.
```bash
composer require spatie/data-transfer-object
```
--------------------------------
### Run Volt Installation Artisan Command
Source: https://ashallendesign.co.uk/blog/laravel-volt
After installing Volt via Composer, run this Artisan command to complete the installation process. Volt will then be ready for use.
```bash
php artisan volt:install
```
--------------------------------
### Install league/commonmark Package
Source: https://ashallendesign.co.uk/blog/working-with-markdown-in-php
Use Composer to install the league/commonmark package for rendering Markdown in PHP.
```bash
composer require league/commonmark
```
--------------------------------
### Install Node.js and npm using Homebrew
Source: https://ashallendesign.co.uk/blog/how-to-set-up-your-mac-for-web-design
Use Homebrew in the Terminal to install Node.js and npm on your Mac. Verify the installation by checking the versions.
```bash
brew install node
```
```bash
node -v npm -v
```
--------------------------------
### Install Honeybadger with API Key
Source: https://ashallendesign.co.uk/blog/a-guide-to-error-and-uptime-monitoring-in-laravel-using-honeybadger
Run the Honeybadger installation command with your API key to generate configuration files and set up the environment variables.
```bash
php artisan honeybadger:install YOUR-API-KEY-HERE
```
--------------------------------
### PHP Inherited Class Setup Method (No Override)
Source: https://ashallendesign.co.uk/blog/the-difference-between-self-static-and-parent-in-php
Shows how a child class inherits and uses the parent's setup method when the child does not define its own. This illustrates basic inheritance.
```php
class FeatureTest extends BaseTestCase
{
//
}
(new FeatureTest())->setUp();
// Output is: "Run base test case set up here...";
```
--------------------------------
### Install Laravel Socialite
Source: https://ashallendesign.co.uk/blog/adding-social-logins-to-your-laravel-apps-twitter-and-github
Install the laravel/socialite package using Composer.
```bash
composer require laravel/socialite
```
--------------------------------
### Install Spatie Laravel Permission Package
Source: https://ashallendesign.co.uk/blog/a-complete-guide-to-managing-user-permissions-in-laravel-apps
Use Composer to install the spatie/laravel-permission package.
```bash
composer require spatie/laravel-permission
```
--------------------------------
### Fetch All User Fields (Inefficient)
Source: https://ashallendesign.co.uk/blog/6-quick-and-easy-ways-to-speed-up-your-laravel-website
This example demonstrates fetching all fields for all users, which can be inefficient due to unnecessary data transfer. It's suitable for basic examples but not recommended for performance-critical applications.
```php
1$users = User::all();
2
3foreach($users as $user) {
4 // Do something here
5}
```
--------------------------------
### Install Laravel Exchange Rates Package
Source: https://ashallendesign.co.uk/blog/how-to-get-currency-exchange-rates-in-laravel
Install the package using Composer. This command adds the necessary files to your project.
```bash
composer require ashallendesign/laravel-exchange-rates
```
--------------------------------
### Install Vonage Laravel SDK
Source: https://ashallendesign.co.uk/blog/integrating-two-factor-authentication-in-laravel-with-vonage
Install the Vonage Laravel package using Composer to interact with the Verify API.
```bash
composer require vonage/vonage-laravel
```
--------------------------------
### Example Message Template Parameters
Source: https://ashallendesign.co.uk/blog/send-whatsapp-messages-in-laravel-with-vonage-s-native-sdk
This example demonstrates how message templates support parameters for customization. The parameters are substituted into the template when sending the message.
```text
1Hello 1. Your order 2 has been shipped.
```
--------------------------------
### Markdown to HTML Conversion Examples
Source: https://ashallendesign.co.uk/blog/working-with-markdown-in-php
Basic Markdown syntax examples and their corresponding HTML output. These demonstrate headings, bold, and italic text.
```markdown
# Heading 1
```
```html
Heading 1
```
```markdown
## Heading 2
```
```html
Heading 2
```
```markdown
**Bold text**
```
```html
Bold text
```
```markdown
_Italic text_
```
```html
Italic text
```
--------------------------------
### Example Markdown Input
Source: https://ashallendesign.co.uk/blog/working-with-markdown-in-php
This is an example of Markdown content that includes the custom '{warning}' syntax.
```markdown
This is some text about a security-related issue.
{warning} This is the warning text
This is after the warning text.
```
--------------------------------
### Install Pusher PHP SDK
Source: https://ashallendesign.co.uk/blog/a-guide-to-using-websockets-in-laravel
Install the Pusher Channels PHP SDK using Composer. This is necessary for integrating with Pusher Channels.
```bash
composer require pusher/pusher-php-server
```
--------------------------------
### Install collect.js using NPM
Source: https://ashallendesign.co.uk/blog/collect-js-a-laravel-like-syntax-for-javascript-arrays
Use this command to install the collect.js library as a dependency in your project via NPM.
```bash
npm install collect.js --save
```
--------------------------------
### Example Laravel Routes
Source: https://ashallendesign.co.uk/blog/how-to-add-breadcrumbs-to-your-laravel-website
This is a basic example of a `routes/web.php` file in a Laravel application, defining routes for user-related pages.
```php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::get('/users/{user}', [UserController::class, 'show'])->name('users.show');
Route::get('/users/{user}/edit', [UserController::class, 'edit'])->name('users.edit');
```
--------------------------------
### Install collect.js using Yarn
Source: https://ashallendesign.co.uk/blog/collect-js-a-laravel-like-syntax-for-javascript-arrays
Use this command to install the collect.js library as a dependency in your project via Yarn.
```bash
yarn add collect.js
```
--------------------------------
### Install Laravel Volt with Composer
Source: https://ashallendesign.co.uk/blog/laravel-volt
Use Composer to install the Livewire Volt package. This is the first step to begin using Volt in your Laravel project.
```bash
composer require livewire/volt
```
--------------------------------
### Examples of Mass Assignment Usages Detected by Enlightn
Source: https://ashallendesign.co.uk/blog/mass-assignment-vulnerabilities-and-validation-in-laravel
These examples show various ways mass assignment can be used, some of which can lead to vulnerabilities if not handled carefully.
```php
$user->forceFill($request->all())->save();
```
```php
User::update($request->all());
```
```php
User::firstOrCreate($request->all());
```
```php
User::upsert($request->all(), []);
```
```php
User::where('user_id', 1)->update($request->all());
```
--------------------------------
### Install Saloon SDK Generator Globally
Source: https://ashallendesign.co.uk/blog/saloon-sdk-generator
Install the Saloon SDK generator package globally using Composer. This makes the CLI tool accessible from any directory.
```bash
composer global require crescat-io/saloon-sdk-generator
```
--------------------------------
### PHP Calling Parent Setup Method (Correct)
Source: https://ashallendesign.co.uk/blog/the-difference-between-self-static-and-parent-in-php
Demonstrates the correct way to extend a parent's method using parent::setUp() to execute both parent and child setup logic without recursion.
```php
class FeatureTest extends BaseTestCase
{
public function setUp(): void
{
parent::setUp();
echo 'Run extra feature test set up here...';
}
}
(new FeatureTest())->setUp();
// Output is: "Run base test case set up here... Run extra feature test set up here...";
```
--------------------------------
### Implement Command Handle Method with Prompts Menu
Source: https://ashallendesign.co.uk/blog/laravel-prompts-api-client
The handle method initializes the GitHub service, displays a welcome message using 'info', and calls 'displayMenu' to present user options via a 'select' prompt.
```php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Interfaces\GitHub\GitHub;
use Illuminate\Console\Command;
use function Laravel\Prompts\info;
use function Laravel\Prompts\select;
final class GitHubCommand extends Command
{
protected $signature = 'github';
protected $description = 'Interact with GitHub using Laravel Prompts';
private GitHub $gitHub;
public function handle(GitHub $gitHub): int
{
$this->gitHub = $gitHub;
info('Interact with GitHub using Laravel Prompts!');
$this->displayMenu();
return self::SUCCESS;
}
private function displayMenu(): void
{
match ($this->getMenuChoice()) {
'list' => $this->listRepositories(),
'create' => $this->createRepository(),
'exit' => null,
};
}
private function getMenuChoice(): string
{
return select(
label: 'Menu:',
options: [
'list' => 'List your public GitHub repositories',
'create' => 'Create a new GitHub repository',
'exit' => 'Exit',
]);
}
}
```
--------------------------------
### Composer Error Example with Vulnerable Package
Source: https://ashallendesign.co.uk/blog/preventing-installing-composer-dependencies-with-known-security-vulnerabilities
This output demonstrates how Composer, with Roave Security Advisories installed, prevents the installation of a package (Laravel Framework v8.22.1) due to a conflict with a known vulnerability. The error message details the conflict and indicates that the installation failed, reverting changes.
```bash
./composer.json has been updated
Running composer update roave/security-advisories
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.
Problem 1
- laravel/framework is locked to version v8.22.1 and an update of this package was not requested.
- roave/security-advisories dev-latest conflicts with illuminate/database <6.20.26|>=7,<7.30.5|>=8,<8.40 (laravel/framework v8.22.1 replaces illuminate/database self.version).
- Root composer.json requires roave/security-advisories dev-latest -> satisfiable by roave/security-advisories[dev-latest].
Installation failed, reverting ./composer.json and ./composer.lock to their original content.
```
--------------------------------
### Get Human-Readable File Size from Storage
Source: https://ashallendesign.co.uk/blog/laravel-human-readable-file-sizes
Combine Laravel's `Storage` facade with `Number::fileSize()` to get the human-readable size of a file stored in your application. This is a practical example for displaying file sizes in a user-friendly way.
```PHP
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Number;
$humanFriendlySize = Number::fileSize(
bytes: Storage::fileSize('example-image.png')
);
```
--------------------------------
### Sequential Process Execution Example
Source: https://ashallendesign.co.uk/blog/processes-and-artisan-commands-in-laravel
Illustrates the sequential execution of a command for multiple files, highlighting the potential time cost compared to concurrent execution.
```php
// 15 seconds to run...
$firstOutput = Process::path(base_path())->run('./convert.sh file-1.png');
$secondOutput = Process::path(base_path())->run('./convert.sh file-1.png');
$thirdOutput = Process::path(base_path())->run('./convert.sh file-1.png');
```
--------------------------------
### Using Get and Set Hooks Together for a Full Name Property
Source: https://ashallendesign.co.uk/blog/php-84-property-hooks
This snippet demonstrates defining a 'fullName' property with both 'get' and 'set' hooks. The 'get' hook constructs the full name from 'firstName' and 'lastName', while the 'set' hook splits a given full name into first and last names. This example highlights computed properties and data manipulation within property definitions.
```php
declare(strict_types=1);
class User
{
public string $fullName {
// Dynamically build up the full name from
// the first and last name
get => $this->firstName.' '.$this->lastName;
// Split the full name into first and last name and
// then set them on their respective properties
set(string $name) {
$splitName = explode(' ', $name);
$this->firstName = $splitName[0];
$this->lastName = $splitName[1];
}
}
public string $firstName {
set(string $name) => $this->firstName = ucfirst($name);
}
public string $lastName {
set(string $name) => $this->lastName = ucfirst($name);
}
public function __construct(string $fullName) {
$this->fullName = $fullName;
}
}
$user = new User(fullName: 'ash allen');
echo $user->firstName; // Ash
echo $user->lastName; // Allen
echo $user->fullName; // Ash Allen
```
--------------------------------
### Basic Pest Test Example
Source: https://ashallendesign.co.uk/blog/architecture-testing-in-laravel-with-pest
A simple Pest test demonstrating the fluent syntax for asserting the correctness of a function. This example shows how to expect a specific output from a function call.
```php
test('add function returns the correct value')
->expect(add(1, 2))
->toBe(3);
```
--------------------------------
### Define Agent Tool with PHP Attribute
Source: https://ashallendesign.co.uk/blog/laragent
Empower your AI agent to perform actions by defining tools using PHP attributes. This example shows a tool to get treasure location.
```php
use LarAgent\Attributes\Tool;
// ...
#[Tool('Get the current treasure location')]
public function getTreasureLocation($island = 'Tortuga') {
return "X marks the spot on {$island}!";
}
```
--------------------------------
### Example services.php Configuration
Source: https://ashallendesign.co.uk/blog/how-to-validate-your-laravel-apps-config
This snippet shows how to define the Fathom API key within the `config/services.php` file.
```php
return [
// ...
'fathom' => [
'api_key' => env('FATHOM_API_KEY'),
],
];
```
--------------------------------
### Basic Profanity Removal Pipeline Stage
Source: https://ashallendesign.co.uk/blog/laravel-pipeline
This example shows a single stage in a Laravel pipeline designed to remove profanity from a given text. It's a good starting point for understanding how individual pipeline stages operate.
```php
declare(strict_types=1);
namespace App\Pipelines\Comments;
use Closure;
final readonly class RemoveProfanity
{
private const array PROFANITIES = [
'fiddlesticks',
'another curse word'
];
public function __invoke(string $comment, Closure $next): string
{
$comment = str_replace(
search: self::PROFANITIES,
replace: '****',
subject: $comment,
);
return $next($comment);
}
}
```
--------------------------------
### Assembling and Running a Laravel Pipeline
Source: https://ashallendesign.co.uk/blog/laravel-pipeline
Demonstrates how to instantiate and run a Laravel Pipeline, passing data through a series of defined stages. The `thenReturn` method is used to get the final result.
```php
use App\Pipelines\Comments\RemoveHarmfulContent;
use App\Pipelines\Comments\RemoveProfanity;
use App\Pipelines\Comments\ShortenUrls;
use Illuminate\Pipeline\Pipeline;
$comment = 'This is a comment with a link to https://honeybadger.io and some fiddlesticks. I hate Laravel!';
$modifiedComment = app(Pipeline::class)
->send($comment)
->through([
RemoveProfanity::class,
RemoveHarmfulContent::class,
ShortenUrls::class,
])
->thenReturn();
```
--------------------------------
### Install laravel-breadcrumbs Package
Source: https://ashallendesign.co.uk/blog/how-to-add-breadcrumbs-to-your-laravel-website
Install the laravel-breadcrumbs package using Composer.
```bash
composer require diglactic/laravel-breadcrumbs
```
--------------------------------
### Implement List Repositories Functionality
Source: https://ashallendesign.co.uk/blog/laravel-prompts-api-client
Fetches repositories using 'getReposFromGitHub', allows the user to select one via a 'select' prompt, displays its information, and provides an option to return to the menu.
```php
declare(strict_types=1);
namespace App\Console\Commands;
use App\Collections\GitHub\RepoCollection;
use App\DataTransferObjects\GitHub\Repo;
use App\Interfaces\GitHub\GitHub;
use Illuminate\Console\Command;
use function Laravel\Prompts\info;
use function Laravel\Prompts\pause;
use function Laravel\Prompts\select;
use function Laravel\Prompts\spin;
final class GitHubCommand extends Command
{
// ...
private function listRepositories(): void
{
$repos = $this->getReposFromGitHub();
$selectedRepoId = select(
label: 'Select a repository:',
options: $repos->mapWithKeys(fn (Repo $repo): array => [$repo->id => $repo->name]),
);
// Find the repo that we just selected.
$selectedRepo = $repos->first(
fn (Repo $repo): bool => $repo->id === $selectedRepoId
);
$this->displayRepoInformation($selectedRepo);
$this->returnToMenu();
}
private function getReposFromGitHub(): RepoCollection
{
return once(function () {
return spin(
callback: fn() => $this->gitHub->listRepos(),
message: 'Fetching your GitHub repositories...'
);
});
}
// ...
}
```
--------------------------------
### Install Lawman Package
Source: https://ashallendesign.co.uk/blog/saloon-lawman-architecture-testing
Install the Lawman package using Composer. Use the --dev flag to ensure it's only installed in your development environment, as it's a testing tool.
```bash
composer require jonpurvis/lawman --dev
```
--------------------------------
### Install Feature Flags Package
Source: https://ashallendesign.co.uk/blog/laravel-implementing-feature-flags
Install the ylsideas/feature-flags package using Composer.
```bash
composer require ylsideas/feature-flags:^2.0
```
--------------------------------
### Display All Dependencies (Including Up-to-Date)
Source: https://ashallendesign.co.uk/blog/composer-outdated
Use the --all option to view all dependencies in your project, not just those with available updates. This provides a comprehensive overview, with green version numbers indicating up-to-date packages.
```bash
composer outdated --all
```
--------------------------------
### Select Input from Options
Source: https://ashallendesign.co.uk/blog/laravel-prompts-api-client
Use the `select` helper to present a list of options to the user for input. The selected option's value is returned.
```PHP
use function Laravel\Prompts\select;
$role = select(
label: 'What is your favorite programming language?',
options: [
'php' => 'PHP',
'js' => 'JavaScript',
'ruby' => 'Ruby',
],
);
```
--------------------------------
### Install Laravel Pennant
Source: https://ashallendesign.co.uk/blog/feature-flags-using-laravel-pennant
Install the Laravel Pennant package using Composer.
```bash
composer require laravel/pennant
```
--------------------------------
### Complete composer.json with Local Repository
Source: https://ashallendesign.co.uk/blog/laravel-package-development-with-local-composer-dependencies
An example of a complete `composer.json` file that includes the local repository configuration. Ensure this file is correctly formatted.
```json
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"require": {
"php": "^8.0.2",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^9.11",
"laravel/sanctum": "^2.14.1",
"laravel/tinker": "^2.7"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/sail": "^1.0.1",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^6.1",
"phpunit/phpunit": "^9.5.10",
"spatie/laravel-ignition": "^1.0"
},
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\Foundation\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true,
"repositories": {
"local": {
"type": "path",
"url": "./packages/*",
"options": {
"symlink": true
}
}
}
}
```
--------------------------------
### Example Plaintext String
Source: https://ashallendesign.co.uk/blog/a-guide-to-encryption-and-hashing-in-laravel
This is the original plaintext message that was encrypted in the previous example.
```plaintext
1This is a secret message.
```
--------------------------------
### Install Profanify with Composer
Source: https://ashallendesign.co.uk/blog/profanify
Install the Profanify package as a development dependency using Composer.
```bash
composer require jonpurvis/profanify --dev
```
--------------------------------
### PHP Recursive Setup Method Call (Incorrect)
Source: https://ashallendesign.co.uk/blog/the-difference-between-self-static-and-parent-in-php
Illustrates an incorrect approach to extending a parent's method by using $this->setUp(), which leads to infinite recursion and a fatal error.
```php
class FeatureTest extends BaseTestCase
{
public function setUp(): void
{
$this->setUp();
echo 'Run extra feature test set up here...';
}
}
(new FeatureTest())->setUp();
```
--------------------------------
### Install LarAgent Package
Source: https://ashallendesign.co.uk/blog/laragent
Use Composer to install the LarAgent package into your Laravel project.
```bash
composer require maestroerror/laragent
```
--------------------------------
### Start a Process and Run Code Asynchronously
Source: https://ashallendesign.co.uk/blog/processes-and-artisan-commands-in-laravel
Use Process::start() to initiate a command and continue executing other PHP code while it runs. The `running()` method checks if the process is still active, allowing for intermittent execution of other tasks before waiting for the process to complete.
```php
use Illuminate\Support\Facades\Process;
public function handle(): void
{
$this->info('Starting installation...');
$extraCodeHasBeenRun = false;
$process = Process::start('./install.sh');
while ($process->running()) {
if (!$extraCodeHasBeenRun) {
$extraCodeHasBeenRun = true;
$this->runExtraCode();
}
}
$result = $process->wait();
$this->info($process->output());
$this->info('Installation complete!');
}
```
--------------------------------
### Default Short URL Example
Source: https://ashallendesign.co.uk/blog/new-features-in-short-url-v6-1-0
Illustrates the default format of a short URL before customization.
```text
1https://example.com/short/ABC123
```
--------------------------------
### Artisan Command Help Output
Source: https://ashallendesign.co.uk/blog/processes-and-artisan-commands-in-laravel
Example output of the `php artisan help` command for a specific Artisan command, detailing its description, usage, and available options.
```bash
❯ php artisan help app:create-super-admin
Description:
Store a new super admin in the database
Usage:
app:create-super-admin [options]
Options:
--email[=EMAIL] The email address of the new user
--password[=PASSWORD] The password of the new user
--name[=NAME] The name of the new user
--send-email Send a welcome email after creating the user
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi|--no-ansi Force (or disable --no-ansi) ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
```
--------------------------------
### Call greet function using named arguments
Source: https://ashallendesign.co.uk/blog/php-named-arguments
Illustrates how to call a PHP function using named arguments, allowing parameters to be passed out of order and improving code readability.
```php
1echo greet(name: 'Ash', greeting: 'Hello');
```
--------------------------------
### Example Button Style with Bootstrap
Source: https://ashallendesign.co.uk/blog/setting-up-tailwind-css-in-laravel
Shows the equivalent button styling using Bootstrap classes for comparison.
```html
```
--------------------------------
### Install Vonage Notification Channel
Source: https://ashallendesign.co.uk/blog/send-an-sms-in-laravel-using-vonage-previously-nexmo
Install the official Laravel notification channel for Vonage using Composer.
```bash
composer require laravel/vonage-notification-channel
```
--------------------------------
### Install PHP CS Fixer
Source: https://ashallendesign.co.uk/blog/php-cs-fixer
Install PHP CS Fixer as a development dependency using Composer.
```bash
composer require friendsofphp/php-cs-fixer --dev
```
--------------------------------
### Navigate to Project Directory
Source: https://ashallendesign.co.uk/blog/round-up-march-2022
Use this command to navigate to your project's directory in the terminal before isolating PHP versions.
```bash
cd your/web/app/path/here
```
--------------------------------
### PHP Calling Parent Setup Method (Order Changed)
Source: https://ashallendesign.co.uk/blog/the-difference-between-self-static-and-parent-in-php
Shows flexibility in calling the parent method by placing parent::setUp() at the end of the child's method, altering the execution order.
```php
class FeatureTest extends BaseTestCase
{
public function setUp(): void
{
echo 'Run extra feature test set up here...';
parent::setUp();
}
}
(new FeatureTest())->setUp();
// Output is: "Run extra feature test set up here... Run base test case set up here...";
```
--------------------------------
### Example User Model with Profanity
Source: https://ashallendesign.co.uk/blog/profanify
This is an example of a PHP User model containing profanity in a docblock comment.
```php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* What the fuck were they thinking when they wrote this?
*
* @return string
*/
public function myMethod(): string
{
return 'Hello!';
}
}
```
--------------------------------
### Install Intervention Image Laravel Package
Source: https://ashallendesign.co.uk/blog/using-intervention-image-in-laravel
Use this Composer command to install the `intervention/image-laravel` package into your Laravel project.
```bash
composer require intervention/image-laravel
```
--------------------------------
### Run Database Migrations
Source: https://ashallendesign.co.uk/blog/a-complete-guide-to-managing-user-permissions-in-laravel-apps
Execute Artisan migrations to create the necessary database tables for roles and permissions.
```bash
php artisan migrate
```
--------------------------------
### Install Symfony Mailer for Mailgun
Source: https://ashallendesign.co.uk/blog/sending-email-in-laravel-with-mailgun
Install the necessary Symfony Mailer components for Mailgun integration using Composer.
```bash
composer require symfony/mailgun-mailer symfony/http-client
```
--------------------------------
### Install Redactable Models Package
Source: https://ashallendesign.co.uk/blog/redact-model-fields-in-laravel
Install the package using Composer. This command adds the necessary files to your project.
```bash
composer require ashallendesign/redactable-models
```
--------------------------------
### Install Laravel Config Validator
Source: https://ashallendesign.co.uk/blog/how-to-validate-your-laravel-apps-config
Install the package using Composer. This command adds the necessary package to your project.
```bash
composer require ashallendesign/laravel-config-validator
```
--------------------------------
### RepositoryManager with if/elseif/else
Source: https://ashallendesign.co.uk/blog/php-match-expression
This code demonstrates how to instantiate a Git repository driver using a series of if/elseif/else statements. It handles different driver names and throws an exception for unsupported ones.
```php
namespace App\Services\Git;
use App\Interfaces\Git\Drivers\RepositoryDriver;
use App\Services\Git\Drivers\BitbucketDriver;
use App\Services\Git\Drivers\GitHubDriver;
use App\Services\Git\Drivers\GitLabDriver;
final readonly class RepositoryManager
{
// ...
public function driver(string $driver): RepositoryDriver
{
if ($driver === 'github') {
return new GitHubDriver();
} elseif ($driver === 'gitlab') {
return new GitLabDriver();
} elseif ($driver === 'bitbucket') {
return new BitbucketDriver();
} else {
throw new \InvalidArgumentException("Unsupported driver: $driver");
}
}
}
```
--------------------------------
### Install baopham/laravel-dynamodb Package
Source: https://ashallendesign.co.uk/blog/dynamodb-laravel
Install the baopham/laravel-dynamodb package via Composer to enable storing Laravel models in DynamoDB.
```bash
composer require baopham/dynamodb
```
--------------------------------
### Creating a User with Named Arguments (Skipping Defaults)
Source: https://ashallendesign.co.uk/blog/php-named-arguments
Illustrates using named arguments to create a user, skipping optional parameters with default values and only specifying the 'locale'.
```php
use App\Services\UserService;
$userService = new UserService();
$user = $userService->createUser(
name: 'Ash',
email: 'mail@ashallendesign.co.uk',
locale: 'es',
);
```
--------------------------------
### Create user with named arguments
Source: https://ashallendesign.co.uk/blog/php-named-arguments
Demonstrates calling the createUser method with named arguments, making the purpose of each parameter explicit and improving code clarity.
```php
1use App\Services\UserService;
$userService = new UserService();
$user = $userService->createUser(
name: 'Ash',
email: 'mail@ashallendesign.co.uk',
sendWelcomeEmail: true,
);
```
--------------------------------
### Using a Specific Driver via app() Helper
Source: https://ashallendesign.co.uk/blog/using-the-manager-pattern-in-laravel
Explicitly select a driver, such as 'open-exchange-rates', using the driver() method on the ExchangeRatesManager resolved via the app() helper, then call exchangeRate.
```php
app(ExchangeRatesManager::class)
->driver('open-exchange-rates')
->exchangeRate(
from: 'GBP',
to: 'USD',
date: Carbon::parse('2021-01-01'),
);
```
--------------------------------
### Invalid JSON Example
Source: https://ashallendesign.co.uk/blog/reading-json-files-in-laravel
An example of an invalid JSON file with a trailing comma, which will cause json_decode to return null.
```json
{
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": [
"framework",
"laravel"
],
}
```
--------------------------------
### Create Repository Logic
Source: https://ashallendesign.co.uk/blog/laravel-prompts-api-client
Creates a new GitHub repository using provided form data and displays a loading spinner. Uses `spin` and `info` Prompts helpers.
```php
// Create an instance of NewRepoData with the form data.
$repoData = new NewRepoData(
name: $formData['repo_name'],
private: $formData['is_private']
);
// Create the repository.
$repo = spin(
fn (): Repo => $this->gitHub->createRepo($repoData),
'Creating repository...',
);
info('Repository created successfully!');
$this->displayRepoInformation($repo);
$this->returnToMenu();
}
```
--------------------------------
### Get Hook with Type Juggling
Source: https://ashallendesign.co.uk/blog/php-84-property-hooks
Demonstrates a 'get' hook where the returned integer is type-juggled to a string property type.
```php
class User
{
public string $fullName {
get {
return 123;
}
}
public function __construct(
public readonly string $firstName,
public readonly string $lastName,
) {
//
}
}
$user = new User(firstName: 'ash', lastName: 'allen');
echo $user->fullName; // "123"
```
--------------------------------
### Basic API Request with Saloon Package
Source: https://ashallendesign.co.uk/blog/round-up-january-2022
This example demonstrates how to create and send a basic API request using the Saloon PHP package. It shows bundling requests into objects for better manageability and testability.
```php
1use App\Http\Saloon\Requests\GetForgeServerRequest;
2
3$request = new GetForgeServerRequest(serverId: '123456');
4
5$response = $request->send();
6$data = $response->json();
```
--------------------------------
### Create Repository Form
Source: https://ashallendesign.co.uk/blog/laravel-prompts-api-client
Displays a form to gather repository name and visibility. Uses the `form` Prompts helper.
```php
private function displayNewRepoForm(): array
{
return form()
->text(
label: 'Repo name:',
required: true,
validate: ['max:100'],
name: 'repo_name'
)
->confirm(
label: 'Private repo?',
name: 'is_private'
)
->submit();
}
```
--------------------------------
### Install jenssegers/agent Package
Source: https://ashallendesign.co.uk/blog/getting-the-user-device-browser-and-os-in-laravel
Install the jenssegers/agent package using Composer to enable user agent detection in your Laravel application.
```bash
composer require jenssegers/agent
```