### Setup Node.js using actions/setup-node Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Installs the latest Node.js version and enables npm caching. This step is necessary for managing and building frontend assets. ```yaml - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: "latest" cache: "npm" ``` -------------------------------- ### Install Composer on Shared Hosting Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting A sequence of commands to install Composer manually on a shared hosting environment if it's not pre-installed. This includes setting an alias and downloading/installing the Composer executable. ```bash echo 'alias composer="php -d allow_url_fopen=On /home/username/composer.phar"' >> ~/.bashrc source ~/.bashrc cd ~ curl -k -O https://getcomposer.org/installer php -d allow_url_fopen=On installer composer -V ``` -------------------------------- ### Laravel Cross Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Generates a cartesian product by combining every row from the 'sizes' table with every row from the 'colors' table. Uses the `crossJoin` method. ```php $sizes = DB::table('sizes') ->crossJoin('colors') ->get(); ``` -------------------------------- ### Install PHP Dependencies with Composer Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Installs PHP dependencies using Composer with optimized flags for a faster and more efficient installation process. This prepares the backend for the application. ```shell run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist ``` -------------------------------- ### Install Composer Dependencies Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Installs the project's dependencies using Composer, specifically excluding development dependencies. This ensures the application has all the necessary libraries to run in a production environment. ```bash composer install --no-dev ``` -------------------------------- ### Install and Build Frontend Dependencies with npm Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Installs frontend dependencies using `npm ci` and builds frontend assets with `npm run build`. This prepares the application's user interface. ```shell run: | npm ci npm run build --if-present ``` -------------------------------- ### Laravel Left Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Retrieves all rows from the 'users' table and matching rows from the 'posts' table, returning null for 'posts' columns if no match is found. Uses the `leftJoin` method. ```php $users = DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); ``` -------------------------------- ### Create .env file from example Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Checks for the existence of a `.env` file and creates one by copying from `.env.example` if it's missing. This ensures the application has its environment configuration. ```shell run: php -r "file_exists('.env') || copy('.env.example', '.env');" ``` -------------------------------- ### Configure .env File Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Copies the example environment file to .env and opens it for editing using nano. This file holds crucial application configuration, including database credentials and environment settings. ```bash cp .env.example .env nano .env ``` -------------------------------- ### Laravel Lateral Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Fetches each user along with their three most recent posts using a lateral join. Requires PostgreSQL, MySQL >= 8.0.14, or SQL Server. Uses `joinLateral`. ```php $latestPosts = DB::table('posts') ->select('id as post_id', 'title as post_title', 'created_at as post_created_at') ->whereColumn('user_id', 'users.id') ->orderBy('created_at', 'desc') ->limit(3);   $users = DB::table('users') ->joinLateral($latestPosts, 'latest_posts') ->get(); ``` -------------------------------- ### Laravel Right Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Retrieves all rows from the 'posts' table and matching rows from the 'users' table, returning null for 'users' columns if no match is found. Uses the `rightJoin` method. ```php $users = DB::table('users') ->rightJoin('posts', 'users.id', '=', 'posts.user_id') ->get(); ``` -------------------------------- ### List Installed PHP Extensions Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Check which PHP extensions are currently enabled on your server. Laravel requires specific extensions to function correctly. ```bash php -m ``` -------------------------------- ### Laravel Subquery Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Joins the 'users' table with a subquery that finds the latest published post for each user. Uses `joinSub` and `DB::raw`. ```php $latestPosts = DB::table('posts') ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at')) ->where('is_published', true) ->groupBy('user_id');   $users = DB::table('users') ->joinSub($latestPosts, 'latest_posts', function ($join) { $join->on('users.id', '=', 'latest_posts.user_id'); }) ->get(); ``` -------------------------------- ### Setup PHP using shivammathur/setup-php Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Sets up a specific PHP version (e.g., 8.3) on the runner. This is crucial for executing PHP-based tasks and managing dependencies with Composer. ```yaml - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: "8.3" ``` -------------------------------- ### Laravel Inner Join Example Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Combines data from multiple tables (users, contacts, orders) returning only rows with matches in all tables. Uses `DB::table` and `join` methods. ```php use Illuminate\Support\Facades\DB;   $users = DB::table('users') ->join('contacts', 'users.id', '=', 'contacts.user_id') ->join('orders', 'users.id', '=', 'orders.user_id') ->select('users.*', 'contacts.phone', 'orders.price') ->get(); ``` -------------------------------- ### Check Laravel Installer Version using Composer Source: https://nabilhassen.com/2-easy-ways-to-check-your-laravel-installer-version This method leverages Composer to display detailed information about the installed 'laravel/installer' package, including its version. This is a reliable alternative if the direct 'laravel' command is not functioning. ```bash composer show laravel/installer ``` -------------------------------- ### Check Laravel Installer Version using Command Source: https://nabilhassen.com/2-easy-ways-to-check-your-laravel-installer-version This method uses the Laravel installer's built-in command to display its version. Ensure the Laravel installer is globally installed and accessible in your system's PATH. ```bash laravel -V ``` ```bash laravel --version ``` -------------------------------- ### Check PHP Version Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Verify the PHP version installed on your server. This is crucial for ensuring compatibility with your Laravel application and its dependencies. ```bash php -v ``` -------------------------------- ### Check Composer Version Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Verify if Composer is installed on your server. Composer is essential for managing Laravel's dependencies. ```bash composer -V ``` -------------------------------- ### Install Laravel 13 (dev) with Laravel Installer Source: https://nabilhassen.com/laravel-13-new-features-release-date-install-now Installs a new Laravel project using the development branch of Laravel 13 via the Laravel installer. Requires PHP 8.3. ```bash laravel new my-app --dev ``` -------------------------------- ### Define Basic API Route in Laravel Source: https://nabilhassen.com/how-to-fix-missing-api-routes-file-in-laravel-12 An example of defining a simple GET route for API users using a closure. When accessed via `/api/users`, it returns a JSON response with user data. ```php use Illuminate\Support\Facades\Route; Route::get('/users', function () { return [ 'name' => 'John Doe', 'email' => 'john@example.com' ]; }); ``` -------------------------------- ### Start Laravel Queue Worker Source: https://nabilhassen.com/how-to-queue-verification-email-in-laravel Starts the queue worker process, which listens for and processes jobs from the configured queue driver. This command is essential for executing background tasks like sending queued emails. ```bash php artisan queue:listen ``` -------------------------------- ### Laravel: `maxByGroup` example Source: https://nabilhassen.com/simplified-grouped-aggregates-in-laravel-query-builder Provides an example of the `maxByGroup` method in Laravel, used to determine the maximum value in each group. This method simplifies data aggregation queries. ```php $maxPrices = DB::table('products')->groupBy('category_id')->maxByGroup('price'); ``` -------------------------------- ### Validating Elements within a Laravel Array Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide This example shows how to validate each element within an array using Laravel's dot notation. It ensures each item in the 'items' array is a string and does not exceed 50 characters. ```php $request->validate([ 'items' => 'required|array', 'items.*' => 'string|max:50', ]); ``` -------------------------------- ### Install Laravel 13 (dev) with Composer Source: https://nabilhassen.com/laravel-13-new-features-release-date-install-now Creates a new Laravel project from the 'dev-master' branch (Laravel 13) using Composer. Requires PHP 8.3. ```bash composer create-project --prefer-dist laravel/laravel my-app dev-master ``` -------------------------------- ### Show All Installed Composer Packages (CLI) Source: https://nabilhassen.com/composer-check-php-package-versions Retrieve a list of all packages installed in your project along with their respective versions using the Composer CLI. This command provides an overview of your project's dependencies. ```bash composer show --installed ``` -------------------------------- ### Laravel Observer Class Example Source: https://nabilhassen.com/3-simple-ways-to-use-eloquent-model-events-in-laravel An example of a Laravel Observer class demonstrating methods for handling 'creating' and 'updating' model events. It shows how to modify model attributes before saving or handle specific attribute changes. ```php namespace App\Observers; use App\Models\User; class UserObserver { public function creating(User $user) { $user->username = strtolower($user->username); } public function updating(User $user) { if ($user->isDirty('email')) { // Handle email changes } } } ``` -------------------------------- ### Get Base URL using Laravel's url() Helper Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Utilizes the built-in url() helper function to get the application's base URL. This is a convenient and commonly used method, especially within Blade views. ```php echo url(''); // https://example.com ``` -------------------------------- ### Customize Validation Error Messages in Laravel Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide Shows how to provide custom error messages for specific validation rules, especially for array elements. This example sets a custom message for the 'max' rule applied to items in an array. ```php $request->validate([ 'items.*' => 'string|max:50', ], [ 'items.*.max' => 'Each item must not exceed 50 characters.', ]); ``` -------------------------------- ### Apply Custom Validation Rule in Laravel Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide Applies a previously defined custom validation rule to a specific array key. This example shows how to validate a 'phone' key within an array of contacts using the `ValidPhoneNumber` rule. ```php use App\Rules\ValidPhoneNumber;   $request->validate([ 'contacts.*.phone' => ['required', new ValidPhoneNumber()], ]); ``` -------------------------------- ### Implement Custom Validation Logic in Laravel Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide Defines the validation logic within a custom rule class. This example checks if a value matches a phone number pattern using a regular expression. It includes a validation method and a message method for custom error reporting. ```php namespace App\Rules;   use Closure; use Illuminate\Contracts\Validation\ValidationRule;   class ValidPhoneNumber implements ValidationRule { public function validate(string $attribute, mixed $value, Closure $fail): void { // Example: Check if the value matches a phone number pattern if(!preg_match('/^\+?[0-9]{10,15}$/', $value)) { $fail('Invalid phone number format.'); } }   public function message() { return 'The :attribute must be a valid phone number.'; } } ``` -------------------------------- ### Get Base URL using Laravel's URL Facade Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Leverages the URL facade to retrieve the application's base URL, offering an alternative to the url() helper. This approach is suitable for those who prefer using facades for application components. ```php use Illuminate\Support\Facades\URL; echo URL::to(''); // https://example.com ``` -------------------------------- ### Laravel Deployment Script Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow A bash script for deploying a Laravel project. It includes commands for switching directories, enabling maintenance mode, pulling latest code, installing dependencies, optimizing the application, clearing caches, and running migrations. It is designed to be executed on the production server. ```bash # Change your Laravel project directory cd ~/mywebsite   # Turn on maintenance mode php artisan down || true   # Pull the latest changes from the git repository git pull origin main   # Install composer dependecies composer install --no-interaction --no-dev   # Optimize view, routes, events, configs php artisan optimize:clear php artisan optimize   # Clear expired password reset tokens php artisan auth:clear-resets   # Run database migrations php artisan migrate --force   # Turn off maintenance mode php artisan up   exit 0 ``` -------------------------------- ### Get Laravel Base URL from Configuration Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Retrieves the application's base URL as defined in the APP_URL setting within the .env file. This method is useful for accessing the configured URL irrespective of the current request context. ```dotenv APP_URL=https://example.com ``` ```php $url = config('app.url'); echo $url; // https://example.com ``` -------------------------------- ### GitHub Actions CI/CD Workflow for Laravel Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow A GitHub Actions workflow defined in YAML that automates testing and deployment of a Laravel project. It checks out the code, sets up PHP and Node.js, copies the .env file, installs dependencies, generates an application key, builds frontend assets, runs tests, and deploys to a server using SSH. ```yaml name: mywebsite.com   on: push: branches: ["main"]   jobs: test-and-deploy: runs-on: ubuntu-latest   steps: - name: Checkout code uses: actions/checkout@v4   - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: "8.3"   - name: Set up Node.js uses: actions/setup-node@v4 with: node-version: "latest" cache: "npm"   - name: Copy .env run: php -r "file_exists('.env') || copy('.env.example', '.env');"   - name: Install PHP Dependencies run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist   - name: Generate key run: php artisan key:generate   - name: Install and Build Frontend Dependencies run: | npm ci npm run build --if-present   - name: Execute tests run: composer test   - name: Deploy to Server uses: appleboy/ssh-action@v1.1.0 with: host: ${{ secrets.SSH_HOST }} username: ${{ secrets.SSH_USER }} key: ${{ secrets.SSH_PRIVATE_KEY }} script: cd scripts && sh deploy_script.sh ``` -------------------------------- ### Laravel Advanced Join with where/orWhere Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Illustrates advanced join conditions using a closure with `on`, `where`, and `orWhere` to filter results based on multiple criteria for 'users' and 'contacts' tables. ```php DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5) ->orWhere('contacts.is_active', true); }) ->get(); ``` -------------------------------- ### Create Database if Not Exists Source: https://nabilhassen.com/sqlstatehy000-1049-unknown-database-fixed This SQL command safely creates a database only if it does not already exist. It's a best practice for setup scripts to prevent errors when databases might already be present. ```sql CREATE DATABASE IF NOT EXISTS db_name; ``` -------------------------------- ### Laravel Advanced Join with orOn Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Demonstrates an advanced join condition using a closure with `orOn` to specify alternative matching criteria between 'users' and 'contacts' tables. ```php DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->orOn('users.email', '=', 'contacts.email'); }) ->get(); ``` -------------------------------- ### Example: Testing Multiple String Searching Methods in PHP Source: https://nabilhassen.com/search-for-a-string-inside-another-string-in-php Demonstrates the practical application of `str_contains()`, `strpos()`, `stripos()`, `preg_match()`, and `strstr()` with a sample haystack and needle, showcasing their respective outputs and usage. ```php $haystack = "The quick brown fox jumps over the lazy dog"; $needle = "fox"; // 1. str_contains (PHP 8+) echo str_contains($haystack, $needle) ? "Found via str_contains\n" : "Not found\n"; // 2. strpos (case‑sensitive) if (strpos($haystack, $needle) !== false) { echo "Found via strpos\n"; } // 3. stripos (case‑insensitive) if (stripos($haystack, strtoupper($needle)) !== false) { echo "Found via stripos\n"; } // 4. preg_match (whole word, case‑insensitive) if (preg_match('/\bfox\b/i', $haystack)) { echo "Found via preg_match (whole word)\n"; } // 5. strstr if (strstr($haystack, $needle) !== false) { echo "Found via strstr. Substring is: " . strstr($haystack, $needle); } ``` -------------------------------- ### Get Scheme and HTTP Host from Laravel Request Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Returns the full base URL including the scheme (http or https), host, and port number. This method provides the complete URL as it appears in the request. ```php public function show(Request $request) { return $request->schemeAndHttpHost(); // https://example.com or https://example.com:8000 } ``` -------------------------------- ### Get HTTP Host with Port from Laravel Request Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Retrieves the host name including the port number if it's specified in the request. This is particularly useful during local development when custom ports are common. ```php public function show(Request $request) { return $request->httpHost(); // example.com or example.com:8000 } ``` -------------------------------- ### Get Host from Laravel Request Object Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Extracts only the host (domain name) from the current HTTP request. This method is ideal when the scheme (http/https) or port number is not required. ```php public function show(Request $request) { return $request->host(); // example.com } ``` -------------------------------- ### Laravel: `avgByGroup` example Source: https://nabilhassen.com/simplified-grouped-aggregates-in-laravel-query-builder Shows how to use the `avgByGroup` method in Laravel to calculate the average value for each group. This method improves query readability and maintainability. ```php $avgRatings = DB::table('reviews')->groupBy('product_id')->avgByGroup('rating'); ``` -------------------------------- ### Get Root URL using Laravel's Request Facade Source: https://nabilhassen.com/7-ways-to-get-your-domain-name-host-in-laravel Accesses the root URL of the current request using the static method of the Request facade. This is beneficial when working outside of controller methods but still needing request context. ```php use Illuminate\Support\Facades\Request; echo Request::root(); // https://example.com ``` -------------------------------- ### Laravel: `minByGroup` example Source: https://nabilhassen.com/simplified-grouped-aggregates-in-laravel-query-builder Demonstrates the usage of the `minByGroup` method in Laravel to find the minimum value within specified groups. It's a concise alternative to older methods. ```php $minSalaries = DB::table('employees')->groupBy('department_id')->minByGroup('salary'); ``` -------------------------------- ### Example of using withoutGlobalScopesExcept with Model Scopes in Laravel Source: https://nabilhassen.com/laravel-1229-disable-all-global-scopes-except-chosen This example shows a Laravel Eloquent model with two global scopes ('published' and 'tenant') defined in its `booted` method. It then demonstrates how to fetch posts while excluding the 'published' scope, retaining only the 'tenant' scope using `withoutGlobalScopesExcept()`. This highlights practical application for selective scope management. ```php class Post extends Model { protected static function booted() { static::addGlobalScope('published', fn ($q) => $q->where('published', true)); static::addGlobalScope('tenant', fn ($q) => $q->where('tenant_id', auth()->id())); } }   // Only keep the tenant scope: $posts = Post::withoutGlobalScopesExcept(['tenant'])->get(); ``` -------------------------------- ### Laravel Memoized Cache Driver: Basic Usage Source: https://nabilhassen.com/laravel-129-introduces-memoized-cache-driver Demonstrates the basic functionality of the memoized cache driver in Laravel. It shows how repeated calls to `Cache::get()` hit the cache, while `Cache::memo()->get()` retrieves values from memory after the first call, reducing overhead. ```php Cache::get('foo'); // hits the cache Cache::get('foo'); // hits the cache Cache::memo()->get('foo'); // hits the cache Cache::memo()->get('foo'); // does NOT hit the cache ``` -------------------------------- ### Test Laravel Action in Isolation (PHP) Source: https://nabilhassen.com/action-pattern-in-laravel-concept-benefits-best-practices Provides an example of unit testing a Laravel Action class independently. It instantiates the action, calls its `handle` method with test data, and then asserts the expected outcome in the database and return value. ```php public function test_it_creates_a_user() { $action = new CreateUser();   $user = $action->handle([ 'name' => 'Jane Doe', 'email' => 'jane@example.com', 'password' => bcrypt('password'), ]);   $this->assertDatabaseHas('users', [ 'email' => 'jane@example.com', ]);   $this->assertEquals('Jane Doe', $user->name); } ``` -------------------------------- ### Build Frontend Locally with npm Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Before deploying, it's recommended to build your frontend assets locally. This command bundles your frontend files for production. ```bash npm run build ``` -------------------------------- ### Show Specific Composer Package Version (CLI) Source: https://nabilhassen.com/composer-check-php-package-versions Use the Composer CLI to display detailed information about a specific installed package, including its version. This is a quick and straightforward method for checking package details. ```bash composer show laravel/framework ``` -------------------------------- ### Broadcast Events with Laravel Actions Source: https://nabilhassen.com/action-pattern-in-laravel-concept-benefits-best-practices Broadcast events to notify frontend clients (e.g., via Reverb or Inertia) when a resource is modified by an action. This example uses the `UserCreated` event. ```php use App\Events\UserCreated; broadcast(new UserCreated($user))->toOthers(); ``` -------------------------------- ### Laravel: `countByGroup` example Source: https://nabilhassen.com/simplified-grouped-aggregates-in-laravel-query-builder Illustrates how to use the `countByGroup` method in Laravel to count records within each group. This method is part of the new grouped aggregate functionalities. ```php $counts = DB::table('users')->groupBy('status')->countByGroup(); ``` -------------------------------- ### Clone Repository and Navigate Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Clones a Git repository into a specified directory ('app') and changes the current directory to the cloned repository. This is the initial step for obtaining the application's source code. ```bash git clone git@github.com:username/repo.git app && cd app ``` -------------------------------- ### Define API Resource Route in Laravel Source: https://nabilhassen.com/how-to-fix-missing-api-routes-file-in-laravel-12 This example demonstrates using `Route::apiResource` to define RESTful routes for a UserController. This is a concise way to manage standard CRUD operations for your API resources. ```php use App\Http\Controllers\Api\UserController; Route::apiResource('users', UserController::class); ``` -------------------------------- ### Composer Package Version in composer.lock Source: https://nabilhassen.com/composer-check-php-package-versions Extract the exact version of an installed Composer package by inspecting the `composer.lock` file. This file precisely records the versions of all packages and their dependencies. ```json { "name": "laravel/framework", "version": "v12.0.1" } ``` -------------------------------- ### Laravel: Get Expired Subscriptions with wherePast() Source: https://nabilhassen.com/laravel-1142-introduces-new-date-query-methods Demonstrates how to use the `wherePast()` method in Laravel Eloquent to retrieve all subscriptions that have already expired, based on their 'expires_at' timestamp. ```php $expiredSubscriptions = Subscription::wherePast('expires_at')->get(); ``` -------------------------------- ### Displaying Validation Errors in Laravel Blade Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide This code demonstrates how to display validation errors in a Laravel Blade template. It iterates through all errors and presents them in an unordered list within a danger alert. ```html @if ($errors->any())
@endif ``` -------------------------------- ### Run Database Migrations Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Executes database migrations to set up the application's database schema. The --force flag is used to bypass confirmation prompts in a production environment. ```bash php artisan migrate --force ``` -------------------------------- ### Validating Arrays with Keys in Laravel Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide This snippet illustrates how to validate specific keys within an array of objects in Laravel. It ensures that each 'product' has a required string 'name' and a required numeric 'price' greater than or equal to 0. ```php $request->validate([ 'products' => 'required|array', 'products.*.name' => 'required|string', 'products.*.price' => 'required|numeric|min:0', ]); ``` -------------------------------- ### Create Custom Validation Rule in Laravel Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide Generates a new custom validation rule class using the Artisan command. This rule can then be implemented with specific validation logic. ```php php artisan make:rule ValidPhoneNumber ``` -------------------------------- ### Combine Query Results with UnionAll in Laravel Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Combines the results of two separate database queries into a single result set, including duplicate rows. Use this when you want to preserve all records from both queries without removing any duplicates, ensuring a complete dataset. ```php use Illuminate\Support\Facades\DB; $first = DB::table('users') ->whereNull('first_name'); $users = DB::table('users') ->whereNull('last_name') ->unionAll($first) ->get(); ``` -------------------------------- ### Basic Array Validation in Laravel Controller Source: https://nabilhassen.com/understanding-array-validation-in-laravel-a-beginners-guide This snippet demonstrates how to validate a request field to ensure it is present and is an array. It is commonly used in controllers to process incoming form data or API requests. ```php use Illuminate\Http\Request; public function store(Request $request) { $request->validate([ 'items' => 'required|array', ]); // Proceed with storing or processing the valid data. } ``` -------------------------------- ### Create Storage Symbolic Link Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Creates a symbolic link for the application's storage directory. This makes the contents of the storage/app/public directory accessible via a public URL. ```bash php artisan storage:link ``` -------------------------------- ### Laravel Memoized Cache Driver: Driver Isolation Source: https://nabilhassen.com/laravel-129-introduces-memoized-cache-driver Demonstrates the isolation of memoized cache stores per driver in Laravel. This example shows that data stored in the Redis memoized driver is separate from data stored in the database memoized driver, ensuring data integrity. ```php Cache::driver('redis')->put('name', 'Taylor in Redis'); Cache::driver('database')->put('name', 'Taylor in the database'); Cache::memo('redis')->get('name'); // "Taylor in Redis" Cache::memo('database')->get('name'); // "Taylor in the database" ``` -------------------------------- ### Generate API Routes File in Laravel Source: https://nabilhassen.com/how-to-fix-missing-api-routes-file-in-laravel-12 This Artisan command generates the `routes/api.php` file, which is not included by default in Laravel 11 and later versions. This allows you to start defining your API endpoints. ```bash php artisan install:api ``` -------------------------------- ### Laravel Memoized Cache Driver: Value Example Source: https://nabilhassen.com/laravel-129-introduces-memoized-cache-driver Illustrates how the memoized cache driver handles value updates in Laravel. It shows that even if a value is updated in the underlying cache, the memoized driver continues to return the previously cached value until the memoization is cleared or refreshed. ```php Cache::put('name', 'Taylor'); Cache::get('name'); // "Taylor" Cache::put('name', 'Tim'); Cache::get('name'); // "Tim" Cache::put('name', 'Taylor'); Cache::memo()->get('name'); // "Taylor" Cache::put('name', 'Tim'); Cache::memo()->get('name'); // "Taylor" ``` -------------------------------- ### Make App Public Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Makes the Laravel application publicly accessible by creating a symbolic link from the application's public directory to the web server's document root (public_html). It also includes backing up the existing public_html. ```bash mv public_html public_html_old ln -s /home/yourusername/app/public /home/yourusername/public_html ``` -------------------------------- ### Optimize Filament Components Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Optimizes Filament components and Blade icons for performance. This Artisan command is specific to projects using the Filament framework. ```bash php artisan filament:optimize ``` -------------------------------- ### Combine Query Results with Union in Laravel Source: https://nabilhassen.com/laravel-joins-explained-clear-guide-with-practical-examples Combines the results of two separate database queries into a single result set, removing duplicate rows. This is useful when you need to fetch data that meets different criteria from the same table and present it as one unified list. ```php use Illuminate\Support\Facades\DB; $first = DB::table('users') ->whereNull('first_name'); $users = DB::table('users') ->whereNull('last_name') ->union($first) ->get(); ``` -------------------------------- ### Get Composer Package Version Programmatically in PHP Source: https://nabilhassen.com/composer-check-php-package-versions Access Composer package versions directly within your PHP application using the `Composer\InstalledVersions` class. This method requires Composer 2.0 or later and allows for dynamic version checking. ```php validate([ 'teams' => 'required|array', 'teams.*.members' => 'required|array', 'teams.*.members.*.name' => 'required|string', 'teams.*.members.*.role' => 'required|string', ]); ``` -------------------------------- ### File Facade - File & Directory Manipulation Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Methods for copying, moving, deleting, and creating files and directories, including symbolic links. ```APIDOC ## POST /website/nabilhassen/file-facade/manipulate ### Description Performs operations like copying, moving, deleting files and directories, and creating symbolic links. ### Method POST ### Endpoint /website/nabilhassen/file-facade/manipulate ### Parameters #### Query Parameters - **operation** (string) - Required - The operation to perform (e.g., 'delete', 'move', 'copy', 'link', 'ensureDirectoryExists', 'makeDirectory', 'moveDirectory', 'copyDirectory', 'deleteDirectory', 'deleteDirectories', 'cleanDirectory'). - **paths** (string|array) - Required for delete/copy/move - The source file/directory path(s). - **target** (string) - Required for move/copy/link - The destination path. - **link** (string) - Required for link - The name of the symbolic link. - **directory** (string) - Required for directory operations - The directory path. - **destination** (string) - Required for copyDirectory - The destination directory. - **preserve** (bool) - Optional for deleteDirectory - Whether to preserve the directory if it is not empty. - **force** (bool) - Optional for makeDirectory - Whether to overwrite if the directory already exists. - **recursive** (bool) - Optional for makeDirectory/ensureDirectoryExists - Whether to create parent directories recursively. - **overwrite** (bool) - Optional for moveDirectory - Whether to overwrite the destination if it exists. - **options** (int) - Optional for copyDirectory - Copy options. - **mode** (int) - Optional for makeDirectory/ensureDirectoryExists - The directory mode. ### Request Body *(Parameters can be sent via query string or request body depending on the operation.)* ### Request Example (Copy File) ``` POST /website/nabilhassen/file-facade/manipulate?operation=copy&path=source.txt&target=destination.txt ``` ### Request Example (Create Directory) ``` POST /website/nabilhassen/file-facade/manipulate?operation=makeDirectory&directory=new_dir&recursive=true&mode=755 ``` ### Response #### Success Response (200) - **message** (string) - Success message indicating the operation performed. #### Response Example ```json { "message": "Directory created successfully." } ``` ``` -------------------------------- ### Generate Application Key Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Generates a unique application key for the Laravel project using the Artisan command. This key is used for encrypting data and securing the application. ```bash php artisan key:generate ``` -------------------------------- ### File Facade - Conditional Logic & Extensibility Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Information on using conditional methods and extending the File Facade with macros. ```APIDOC ## GET /website/nabilhassen/file-facade/extensibility ### Description Details on using conditional execution methods (`when`, `unless`) and extending the File Facade using the macro system. ### Method GET ### Endpoint /website/nabilhassen/file-facade/extensibility ### Parameters *(No direct parameters for retrieving documentation on these concepts.)* ### Response #### Success Response (200) - **conditionalMethods** (array) - List of conditional methods (`when`, `unless`). - **macroMethods** (array) - List of macro management methods (`macro`, `mixin`, `hasMacro`, `flushMacros`). - **description** (string) - Explanation of how to use these features. #### Response Example ```json { "conditionalMethods": [ "when", "unless" ], "macroMethods": [ "macro", "mixin", "hasMacro", "flushMacros" ], "description": "Use 'when(condition, callable)' or 'unless(condition, callable)' for conditional file operations. Register custom logic using File::macro('methodName', function() { ... })." } ``` ``` -------------------------------- ### Laravel File Facade: Symlinks and Custom Macros Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Shows how to create symbolic links using the File facade and how to extend its functionality by defining custom macros for specific file operations like duplication and deletion. ```php // Symlinks File::link($targetFile, $symlink);   // Custom macro File::macro('duplicateAndDelete', function ($path) { File::copy($path, $path.'.dup'); File::delete($path); }); ``` -------------------------------- ### Querying posts attached to specific tags (After) Source: https://nabilhassen.com/new-in-laravel-127-whereattachedto-for-belongstomany-relationships This example showcases the new `whereAttachedTo()` method in Laravel 12.7, providing a concise and readable way to achieve the same result as the 'Before' example. ```php $tags = Tag::where('created_at', '>', now()->subMonth())->get(); $taggedPosts = Post::whereAttachedTo($tags)->get(); ``` -------------------------------- ### Laravel File Facade: Inline Replacements and Directory Management Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Illustrates how to use the File facade for performing inline search and replace operations within files and managing directories, including ensuring their existence and cleaning them. ```php // Inline replacements File::replaceInFile('TODO', 'DONE', $filePath);   // Directory management File::ensureDirectoryExists($dirPath); File::cleanDirectory($dirPath); ``` -------------------------------- ### File Facade - Facade & Testing Tools Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Overview of methods inherited from the base Facade class, useful for testing and mocking. ```APIDOC ## GET /website/nabilhassen/file-facade/testing ### Description Lists and describes methods inherited from Laravel's base Facade class, which are primarily used for testing and mocking the File Facade. ### Method GET ### Endpoint /website/nabilhassen/file-facade/testing ### Parameters *(No direct parameters for retrieving documentation on these concepts.)* ### Response #### Success Response (200) - **testingMethods** (array) - List of facade testing methods. - **description** (string) - Explanation of their purpose in testing. #### Response Example ```json { "testingMethods": [ "resolved", "spy", "partialMock", "shouldReceive", "expects", "swap", "isFake", "getFacadeRoot", "getFacadeAccessor", "resolveFacadeInstance" ], "description": "These methods allow you to mock, spy on, and manage the lifecycle of the File Facade during your tests." } ``` ``` -------------------------------- ### Update Environment Settings Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Sets key environment variables within the .env file for a production environment. This includes disabling debug mode and configuring database connection details. ```bash APP_ENV=production APP_DEBUG=false DB_HOST=localhost DB_CONNECTION=mysql DB_DATABASE=yourdbname DB_USERNAME=youruser DB_PASSWORD=yourpass ``` -------------------------------- ### Laravel Deployment Command Sequence Source: https://nabilhassen.com/php-artisan-cacheclear-what-it-does-and-what-it-does-not Demonstrates a common sequence of Artisan commands used in Laravel deployments, specifically caching configuration, routes, events, and views, followed by clearing the application cache. ```php # Optimize view, routes, events, configs php artisan optimize   # Clear caches php artisan cache:clear ``` -------------------------------- ### Set Up Cron Job for Scheduled Tasks Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Configures a cron job to run Laravel's scheduler, which executes any defined scheduled tasks. The output is redirected to /dev/null to prevent email notifications for every execution. ```bash /usr/local/bin/php /home/yourusername/app/artisan schedule:run >> /dev/null 2>&1 ``` -------------------------------- ### Check for Existing SSH Key Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting This command checks if an SSH public key already exists in your user's .ssh directory. It's a prerequisite for setting up Git deployment keys. ```bash cat ~/.ssh/id_rsa.pub ``` -------------------------------- ### Laravel File Facade: Stream, Write, and Parse JSON Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Demonstrates using the File facade for streaming file lines, performing lock-safe writes, and parsing JSON content. These operations are essential for efficient file handling in Laravel applications. ```php // Stream file safely File::lines($path)->each(fn($line) => process($line));   // Lock‑safe write File::put($path, $contents, true);   // Parse JSON $data = File::json($configFile, JSON_THROW_ON_ERROR, true); ``` -------------------------------- ### Checkout Code using actions/checkout Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Downloads the repository code to the runner environment. This is a fundamental step to ensure the workflow has access to the application files. ```yaml - name: Checkout code uses: actions/checkout@v4 ``` -------------------------------- ### Generate SSH Key Source: https://nabilhassen.com/how-to-deploy-laravel-on-shared-hosting Generates a new SSH key pair (public and private) for your cPanel user. This key will be used to authenticate with Git repositories for deployment. ```bash ssh-keygen -t rsa -b 4096 -C "your_cpanel_username" ``` -------------------------------- ### Querying posts attached to specific tags (Before) Source: https://nabilhassen.com/new-in-laravel-127-whereattachedto-for-belongstomany-relationships This example demonstrates the older, more verbose method of querying posts that are associated with a collection of tags using `whereHas`. ```php $tags = Tag::where('created_at', '>', now()->subMonth())->get(); $taggedPosts = Post::whereHas('tags', function ($query) use ($tags) { $query->whereKey($tags); })->get(); ``` -------------------------------- ### Execute Tests with Composer Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Runs the application's tests using a Composer command, typically `composer test`. This step validates the application's functionality. ```shell run: composer test ``` -------------------------------- ### File Facade - Integrity, Hashing & Comparisons Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Methods for calculating file hashes and comparing file content integrity. ```APIDOC ## GET /website/nabilhassen/file-facade/integrity ### Description Computes file hashes and compares the integrity of two files. ### Method GET ### Endpoint /website/nabilhassen/file-facade/integrity ### Parameters #### Query Parameters - **path** (string) - Required - The path to the file for hashing. - **algorithm** (string) - Optional - The hashing algorithm to use (default: 'md5'). - **firstFile** (string) - Required for comparison - The path to the first file. - **secondFile** (string) - Required for comparison - The path to the second file. ### Response #### Success Response (200) - **hash** (string) - The computed hash of the file. - **hasSameHash** (bool) - True if both files have the same hash, false otherwise. #### Response Example ```json { "hash": "d41d8cd98f00b204e9800998ecf8427e" } ``` #### Response Example (Comparison) ```json { "hasSameHash": true } ``` ``` -------------------------------- ### File Facade - Writing & Text Modifications Source: https://nabilhassen.com/file-facade-in-laravel-unofficial-documentation Methods for writing content to files, performing replacements, and modifying file permissions. ```APIDOC ## POST /website/nabilhassen/file-facade/write ### Description Writes content to files, performs inline replacements, and modifies file permissions. ### Method POST ### Endpoint /website/nabilhassen/file-facade/write ### Parameters #### Query Parameters - **path** (string) - Required - The path to the file. - **contents** (string) - Required for 'put' - The content to write. - **lock** (bool) - Optional - Whether to lock the file during writing (default: false). - **search** (string|array) - Required for 'replaceInFile' - The string or array of strings to search for. - **replace** (string|array) - Required for 'replaceInFile' - The string or array of strings to replace with. - **data** (string) - Required for 'prepend'/'append' - The data to add. - **mode** (int) - Optional - The file mode for 'replace'. - **chmodMode** (int) - Optional - The mode for 'chmod'. ### Request Body *(Parameters can be sent via query string or request body depending on the operation. For simplicity, examples show query parameters.)* ### Request Example (Put) ``` POST /website/nabilhassen/file-facade/write?path=example.txt&contents=Hello%20World ``` ### Request Example (ReplaceInFile) ``` POST /website/nabilhassen/file-facade/write?path=example.txt&search=TODO&replace=DONE ``` ### Response #### Success Response (200) - **message** (string) - Success message indicating the operation performed. #### Response Example ```json { "message": "File content written successfully." } ``` ``` -------------------------------- ### Generate Laravel Application Key Source: https://nabilhassen.com/deploy-laravel-project-with-github-actions-cicd-workflow Executes the `php artisan key:generate` command to create a new encryption key for the Laravel application, ensuring security. ```shell run: php artisan key:generate ```