### 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())