### Laravel Request: Getting Input Data (Multiple Methods vs. Helper) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet compares different ways to access request input. It shows how `Request::get('name')` and `$request->input('name')` can be simplified to `$request->name` or `request('name')` for better readability. ```PHP $request->input('name'), Request::get('name') ``` ```PHP $request->name, request('name') ``` -------------------------------- ### Laravel Session: Getting Session Data (Static vs. Helper) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates replacing the static `Session::get('cart')` call with the more convenient and readable `session('cart')` helper function for retrieving session data. ```PHP Session::get('cart') ``` ```PHP session('cart') ``` -------------------------------- ### Laravel Session: Accessing Session Data (Request vs. Helper) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet compares verbose and concise ways to retrieve data from the session in Laravel. It demonstrates replacing `$request->session()->get('cart')` with the more readable `session('cart')` helper function. ```PHP $request->session()->get('cart'); ``` ```PHP session('cart'); ``` -------------------------------- ### Laravel Helpers: Getting Current Date/Time Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates using Laravel's built-in helper functions `now()` and `today()` as a shorthand for `Carbon::now()` and `Carbon::today()`, making date/time operations more concise. ```PHP Carbon::now(), Carbon::today() ``` ```PHP now(), today() ``` -------------------------------- ### Laravel Concise Syntax Examples Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/burmese.md This section provides a comprehensive list of common Laravel syntax patterns and their more concise, readable alternatives. It covers various helpers and methods for session management, request handling, redirects, null-safe operations, view data passing, conditional assignments, date/time utilities, service container access, and Eloquent queries. Adopting these concise forms improves code brevity and expressiveness. ```PHP Session::get('cart') ``` ```PHP session('cart') ``` ```PHP $request->session()->get('cart') ``` ```PHP session('cart') ``` ```PHP Session::put('cart', $data) ``` ```PHP session(['cart' => $data]) ``` ```PHP $request->input('name'), Request::get('name') ``` ```PHP $request->name, request('name') ``` ```PHP return Redirect::back() ``` ```PHP return back() ``` ```PHP is_null($object->relation) ? null : $object->relation->id ``` ```PHP optional($object->relation)->id ``` ```PHP $object->relation?->id ``` ```PHP return view ``` -------------------------------- ### Processing All Data at Once Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet retrieves all records at once using `$this->get()` and then iterates through them. For large datasets, this can consume excessive memory and lead to performance issues or out-of-memory errors. ```php $users = $this->get(); foreach ($users as $user) { ... } ``` -------------------------------- ### Delegating Business Logic to Service Class - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This example demonstrates moving business logic, such as file handling, into a dedicated service class (`ArticleService`). The controller's `store` method now delegates the task to the service, keeping the controller 'skinny' and focused on request orchestration. This improves modularity, testability, and reusability of the business logic. It depends on the `ArticleService` and the uploaded `image` file. ```PHP public function store(Request $request) { $this->articleService->handleUploadedImage($request->file('image')); ... } class ArticleService { public function handleUploadedImage($image): void { if (!is_null($image)) { $image->move(public_path('images') . 'temp'); } } } ``` -------------------------------- ### Correct Full Name Attribute Implementation with SRP (PHP) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/italian.md This PHP example demonstrates the Single Responsibility Principle by refactoring the full name accessor into smaller, focused methods. `getFullNameAttribute` orchestrates, while `isVerifiedClient`, `getFullNameLong`, and `getFullNameShort` each handle a single, distinct responsibility, improving readability and maintainability. ```PHP public function getFullNameAttribute(): string { return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort(); } public function isVerifiedClient(): bool { return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified(); } public function getFullNameLong(): string { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } public function getFullNameShort(): string { return $this->first_name[0] . '. ' . $this->last_name; } ``` -------------------------------- ### Laravel Eloquent: Selecting Specific Columns Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates a more concise way to select specific columns when retrieving records using Eloquent. It shows that `->get(['id', 'name'])` is a shorthand for `->select('id', 'name')->get()`. ```PHP ->select('id', 'name')->get() ``` ```PHP ->get(['id', 'name']) ``` -------------------------------- ### Extracting Business Logic to Service Class in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This example demonstrates moving business logic, specifically file handling, into a dedicated `ArticleService` class. The controller now delegates this responsibility, keeping itself lean and focused on request handling, which significantly improves modularity, reusability, and testability of the application. ```PHP public function store(Request $request) { $this->articleService->handleUploadedImage($request->file('image')); ... } class ArticleService { public function handleUploadedImage($image) { if (!is_null($image)) { $image->move(public_path('images') . 'temp'); } } } ``` -------------------------------- ### Laravel Request: Getting Input with Default Value Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates a more concise way to retrieve a request value and provide a default if it's not present. It replaces a ternary operator with the `$request->get('value', 'default')` method. ```PHP $request->has('value') ? $request->value : 'default'; ``` ```PHP $request->get('value', 'default') ``` -------------------------------- ### Retrieving Clients with Model-Encapsulated Logic - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This example demonstrates 'Fat Models, Skinny Controllers'. The controller's `index` method is simplified by delegating the complex data retrieval logic to a method (`getWithNewOrders`) within the `Client` Eloquent model. This keeps the controller focused on handling requests and views, while the model encapsulates database-related concerns. It depends on the `Client` model and `Collection` return type. ```PHP public function index() { return view('index', ['clients' => $this->client->getWithNewOrders()]); } class Client extends Model { public function getWithNewOrders(): Collection { return $this->verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); } } ``` -------------------------------- ### Refactoring Database Logic to Model in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This example demonstrates the 'Fat Models, Skinny Controllers' principle by moving the database query logic into the `Client` model's `getWithNewOrders` method. The controller now only delegates the data retrieval, keeping itself lean and focused on preparing the view, improving modularity and testability. ```PHP public function index() { return view('index', ['clients' => $this->client->getWithNewOrders()]); } class Client extends Model { public function getWithNewOrders() { return $this->verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); } } ``` -------------------------------- ### Eager Loading Related Data for Blade Templates Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates eager loading user profiles using `User::with('profile')->get()` before iterating in the Blade template. This resolves the N+1 problem by fetching all users and their associated profiles in just two queries, significantly improving performance. ```php $users = User::with('profile')->get(); @foreach ($users as $user) {{ $user->profile->name }} @endforeach ``` -------------------------------- ### Applying Single Responsibility Principle in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/arabic.md This example refactors the previous method to adhere to the Single Responsibility Principle. Each new method (isVerifiedClient, getFullNameLong, getFullNameShort) now has a single, clear responsibility, making the code more modular, readable, and easier to test and maintain. ```php public function getFullNameAttribute(): string { return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort(); } public function isVerifiedClient(): bool { return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified(); } public function getFullNameLong(): string { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } public function getFullNameShort(): string { return $this->first_name[0] . '. ' . $this->last_name; } ``` -------------------------------- ### Laravel Helpers: Safely Accessing Optional Properties Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates using the `optional()` helper to safely access properties of an object that might be null, preventing 'Trying to get property of non-object' errors. It also mentions the PHP 8 nullsafe operator `?->` as an alternative. ```PHP is_null($object->relation) ? null : $object->relation->id ``` ```PHP optional($object->relation)->id (in PHP 8: $object->relation?->id) ``` -------------------------------- ### Accessing Session and Input Data Verbose (Bad) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/burmese.md This snippet illustrates verbose ways to access session data and request input in Laravel. Using $request->session()->get('cart') and $request->input('name') is functional but less concise than available helper functions and dynamic properties. This can make the code longer and less readable. ```PHP $request->session()->get('cart'); $request->input('name'); ``` -------------------------------- ### Retrieving Data from HTML Attributes in JavaScript Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet shows how JavaScript can retrieve data that was embedded in an HTML element's attribute. It uses jQuery to get the value of a hidden input field, demonstrating a cleaner separation of concerns between PHP and JavaScript. ```javascript let article = $('#article').val(); ``` -------------------------------- ### Violating Single Responsibility Principle in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/arabic.md This example demonstrates a method that violates the Single Responsibility Principle by combining multiple concerns: determining user type/verification and formatting a full name. This makes the method harder to read, test, and maintain. ```php public function getFullNameAttribute(): string { if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } else { return $this->first_name[0] . '. ' . $this->last_name; } } ``` -------------------------------- ### Using Form Request for Data Validation in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This example demonstrates using a dedicated Form Request class (`PostRequest`) for data validation. This approach cleanly separates validation logic from the controller, making the controller leaner, validation rules reusable, and improving overall code organization and testability. ```PHP public function store(PostRequest $request) { ... } class PostRequest extends Request { public function rules() { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]; } } ``` -------------------------------- ### Externalized Request Validation with Form Requests - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This example demonstrates moving validation logic to a dedicated Form Request class (`PostRequest`). The controller's `store` method becomes cleaner, only accepting an already validated request. This centralizes validation rules, promotes reusability, and improves testability. It depends on the `PostRequest` class extending `Request`. ```PHP public function store(PostRequest $request) { ... } class PostRequest extends Request { public function rules(): array { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]; } } ``` -------------------------------- ### Reusing Query Logic with Eloquent Scopes - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This example demonstrates applying the DRY principle using Eloquent local scopes. The common 'active' query logic is encapsulated in a `scopeActive` method. This scope can then be reused across different queries (`getActive`, `getArticles`), eliminating duplication and centralizing the definition of 'active' records. This improves maintainability and readability. It depends on Eloquent models and query scopes. ```PHP public function scopeActive($q) { return $q->where('verified', true)->whereNotNull('deleted_at'); } public function getActive(): Collection { return $this->active()->get(); } public function getArticles(): Collection { return $this->whereHas('user', function ($q) { $q->active(); })->get(); } ``` -------------------------------- ### Duplicated Query Logic for Active Records - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This example shows duplicated query logic for determining 'active' records across two different methods (`getActive` and `getArticles`). The conditions `where('verified', 1)->whereNotNull('deleted_at')` are repeated, violating the Don't Repeat Yourself (DRY) principle. This makes maintenance difficult and prone to errors if the 'active' definition changes. It depends on Eloquent query builder methods. ```PHP public function getActive() { return $this->where('verified', 1)->whereNotNull('deleted_at')->get(); } public function getArticles() { return $this->whereHas('user', function ($q) { $q->where('verified', 1)->whereNotNull('deleted_at'); })->get(); } ``` -------------------------------- ### Laravel Redirect: Redirecting Back (Static vs. Helper) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates a more concise way to redirect the user to the previous page. It replaces `Redirect::back()` with the simpler `back()` helper function. ```PHP return Redirect::back() ``` ```PHP return back() ``` -------------------------------- ### Creating Article with Manual Property Assignment Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates creating an `Article` instance and manually assigning each property from the request. This approach is verbose and prone to errors, especially when dealing with many fields, and does not leverage Laravel's mass assignment capabilities. ```php $article = new Article; $article->title = $request->title; $article->content = $request->content; $article->verified = $request->verified; // Add category to article $article->category_id = $category->id; $article->save(); ``` -------------------------------- ### Laravel Container: Resolving Services Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates a more concise way to resolve services from Laravel's service container. It replaces `App::make('Class')` with the `app('Class')` helper function. ```PHP App::make('Class') ``` ```PHP app('Class') ``` -------------------------------- ### Initializing Objects with IoC Container in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates the preferred way to initialize classes in Laravel using the Inversion of Control (IoC) container or dependency injection, rather than direct instantiation with 'new'. This approach reduces tight coupling between classes and simplifies testing by allowing dependencies to be easily mocked or swapped. ```php $user = new User; $user->create($request->validated()); ``` ```php public function __construct(protected User $user) {} ... $this->user->create($request->validated()); ``` -------------------------------- ### Modern PHP Method Documentation and Type Hinting Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet advocates for using modern PHP features like descriptive method names and return type hints instead of traditional DocBlocks for documenting function purpose and parameters. This approach enhances code readability and leverages PHP's built-in type checking capabilities, making the code self-documenting and reducing verbosity. ```php /** * The function checks if given string is a valid ASCII string * * @param string $string String we get from frontend which might contain * illegal characters. Returns True is the string * is valid. * * @return bool * @author John Smith * * @license GPL */ public function checkString($string) { } ``` ```php public function isValidAsciiString(string $string): bool { } ``` -------------------------------- ### Laravel Model: Convention Over Configuration (Good Practice) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet showcases the 'convention over configuration' principle in Laravel. By adhering to standard naming conventions (e.g., 'customers' for the table, 'id' for the primary key), the model implicitly handles these details, resulting in cleaner and more concise code for relationships. ```PHP // Table name 'customers' // Primary key 'id' class Customer extends Model { public function roles(): BelongsToMany { return $this->belongsToMany(Role::class); } } ``` -------------------------------- ### Using Constants and Localization for Strings Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates using a class constant (`Article::TYPE_NORMAL`) for type comparison and a localization helper (`__('app.article_added')`) for a flash message. This improves maintainability, allows for easy localization, and makes the code more robust. ```php public function isNormal() { return $article->type === Article::TYPE_NORMAL; } return back()->with('message', __('app.article_added')); ``` -------------------------------- ### Accessing Configuration Data in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates the recommended method for accessing application configuration data in Laravel. Instead of directly using 'env()' to retrieve values from the '.env' file, data should be passed to a config file (e.g., 'config/api.php') and then accessed via the 'config()' helper function. This provides a more structured, cached, and secure approach to configuration management. ```php $apiKey = env('API_KEY'); ``` ```php // config/api.php 'key' => env('API_KEY'), // Use the data $apiKey = config('api.key'); ``` -------------------------------- ### Accessing Session and Input Data Concisely (Good) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/burmese.md This snippet demonstrates more concise and readable ways to access session data and request input in Laravel. Using the session() helper function and dynamic properties like $request->name simplifies the code, making it shorter and easier to read. This aligns with Laravel's philosophy of providing expressive syntax. ```PHP session('cart'); $request->name; ``` -------------------------------- ### Laravel Session: Storing Session Data (Static vs. Helper) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates a more concise way to store data in the session using the `session()` helper. It replaces `Session::put('cart', $data)` with `session(['cart' => $data])` for a more array-like assignment. ```PHP Session::put('cart', $data) ``` ```PHP session(['cart' => $data]) ``` -------------------------------- ### Laravel Views: Passing Data with compact() Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates a cleaner way to pass multiple variables to a Laravel view using the `compact()` PHP function. It replaces chained `with()` calls with a single `compact()` call, improving readability. ```PHP return view('index')->with('title', $title)->with('client', $client) ``` ```PHP return view('index', compact('title', 'client')) ``` -------------------------------- ### Calculating Full Name with Focused Methods - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This set of methods demonstrates how to break down complex logic into smaller, focused functions. `getFullNameAttribute` acts as an orchestrator, delegating the conditional check to `isVerifiedClient` and name formatting to `getFullNameLong` and `getFullNameShort`. This improves readability, testability, and reusability. Dependencies include `auth()->user()` and user properties (`first_name`, `middle_name`, `last_name`). ```PHP public function getFullNameAttribute(): string { return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort(); } public function isVerifiedClient(): bool { return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified(); } public function getFullNameLong(): string { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } public function getFullNameShort(): string { return $this->first_name[0] . '. ' . $this->last_name; } ``` -------------------------------- ### Creating Article with Eloquent Mass Assignment Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet shows a more efficient way to create an `Article` using Eloquent's mass assignment feature via a relationship. It leverages `create` on the `article` relationship of a `category` and passes validated request data, making the code concise and secure. ```php $category->article()->create($request->validated()); ``` -------------------------------- ### Applying Single Responsibility Principle in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This set of methods demonstrates the Single Responsibility Principle by breaking down the `getFullNameAttribute` into smaller, focused methods. `isVerifiedClient` handles verification, while `getFullNameLong` and `getFullNameShort` handle specific name formatting, leading to cleaner and more maintainable code. ```PHP public function getFullNameAttribute(): string { return $this->isVerifiedClient() ? $this->getFullNameLong() : $this->getFullNameShort(); } public function isVerifiedClient(): bool { return auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified(); } public function getFullNameLong(): string { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } public function getFullNameShort(): string { return $this->first_name[0] . '. ' . $this->last_name; } ``` -------------------------------- ### Updating Resource with Single Responsibility - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `update` method adheres to the Single Responsibility Principle by delegating event logging to a `logService` and event updating to an `event` service. It focuses solely on orchestrating the update process, making the method cleaner and more maintainable. Dependencies include `UpdateRequest`, `LogService`, and `Event` services. ```PHP public function update(UpdateRequest $request): string { $this->logService->logEvents($request->events); $this->event->updateGeneralEvent($request->validated()); return back(); } ``` -------------------------------- ### Retrieving Clients with Business Logic in Controller - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `index` method in a controller directly contains Eloquent query logic, including `with` and `where` clauses, violating the 'Fat Models, Skinny Controllers' principle. The controller is responsible for data retrieval details instead of delegating it to the model. It depends on the `Client` model and `Carbon` for date manipulation. ```PHP public function index() { $clients = Client::verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); return view('index', ['clients' => $clients]); } ``` -------------------------------- ### Using Hardcoded Strings and Magic Values Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet uses hardcoded string literals ('normal') for type comparison and a direct string for a flash message. This approach makes the code less maintainable, harder to localize, and prone to errors if the string changes. ```php public function isNormal(): bool { return $article->type === 'normal'; } return back()->with('message', 'Your article has been added!'); ``` -------------------------------- ### Laravel Request: Accessing Input Data (Input Method vs. Property) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates a more concise way to access request input in Laravel. It replaces `$request->input('name')` with the direct property access `$request->name`, which is more idiomatic and readable. ```PHP $request->input('name'); ``` ```PHP $request->name; ``` -------------------------------- ### Processing Data in Chunks Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates processing data in smaller chunks using `$this->chunk(500, ...)`. This approach retrieves and processes records in batches of 500, significantly reducing memory consumption and improving performance for data-heavy tasks. ```php $this->chunk(500, function ($users) { foreach ($users as $user) { ... } }); ``` -------------------------------- ### Querying Articles with Raw SQL Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates a complex database query written in raw SQL to retrieve articles. It involves multiple nested EXISTS subqueries to check for related users and profiles, and filters by verified, active, and deleted_at status. This approach is less readable and harder to maintain compared to Eloquent. ```sql SELECT * FROM `articles` WHERE EXISTS (SELECT * FROM `users` WHERE `articles`.`user_id` = `users`.`id` AND EXISTS (SELECT * FROM `profiles` WHERE `profiles`.`user_id` = `users`.`id`) AND `users`.`deleted_at` IS NULL) AND `verified` = '1' AND `active` = '1' ORDER BY `created_at` DESC ``` -------------------------------- ### Checking Joins with a Descriptive Method Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet uses a descriptive method `$this->hasJoins()` to check for the presence of joins. This improves code readability and self-documentation, eliminating the need for a clarifying comment and encapsulating the logic within a well-named method. ```php if ($this->hasJoins()) ``` -------------------------------- ### Querying Articles with Eloquent Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet shows the Eloquent ORM approach to retrieve articles. It uses `has` to check for related `user` and `profile` relationships, a `verified` scope, and `latest` to order by creation date. This method is more concise, readable, and leverages Laravel's built-in features. ```php Article::has('user.profile')->verified()->latest()->get(); ``` -------------------------------- ### Checking Joins with Direct Property Access Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet checks for the presence of joins by directly accessing the `joins` property of the query builder and counting its elements. While functional, it requires a comment to explain its purpose and is less readable due to the direct property access. ```php // Determine if there are any joins if (count((array) $builder->getQuery()->joins) > 0) ``` -------------------------------- ### Laravel Model: Explicit Configuration (Bad Practice) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates a bad practice where a Laravel model explicitly defines table name, primary key, and relationship pivot table details. This is unnecessary when Laravel's conventions can infer these details, leading to verbose code. ```PHP // Table name 'Customer' // Primary key 'customer_id' class Customer extends Model { const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; protected $table = 'Customer'; protected $primaryKey = 'customer_id'; public function roles(): BelongsToMany { return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); } } ``` -------------------------------- ### Laravel Eloquent: Ordering by Oldest Creation Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates using the `oldest()` Eloquent method as a shorthand for `orderBy('created_at', 'asc')`, providing a more semantic and concise way to order results by creation date in ascending order. ```PHP ->orderBy('created_at', 'asc') ``` ```PHP ->oldest() ``` -------------------------------- ### Laravel Eloquent: Ordering by Latest Creation Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates using the `latest()` Eloquent method as a shorthand for `orderBy('created_at', 'desc')`, providing a more semantic and concise way to order results by creation date in descending order. ```PHP ->orderBy('created_at', 'desc') ``` ```PHP ->latest() ``` -------------------------------- ### Handling File Uploads Directly in Controller - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `store` method contains business logic for handling file uploads directly within the controller. This violates the Single Responsibility Principle for controllers, which should primarily coordinate requests, not implement detailed business operations. It depends on the `Request` object and file system operations (`move`). ```PHP public function store(Request $request) { if ($request->hasFile('image')) { $request->file('image')->move(public_path('images') . 'temp'); } ... } ``` -------------------------------- ### Updating Resource with Multiple Responsibilities - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `update` method violates the Single Responsibility Principle by handling request validation, logging events, and updating the general event. It mixes concerns that should be separated into distinct responsibilities. Dependencies include `Request`, `Carbon` (for date parsing), `Logger`, and `Event` services. ```PHP public function update(Request $request): string { $validated = $request->validate([ 'title' => 'required|max:255', 'events' => 'required|array:date,type' ]); foreach ($request->events as $event) { $date = $this->carbon->parse($event['date'])->toString(); $this->logger->log('Update event ' . $date . ' :: ' . $); } $this->event->updateGeneralEvent($request->validated()); return back(); } ``` -------------------------------- ### Handling Dates with Carbon and Eloquent Casts in Laravel Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates the best practice for handling dates in Laravel applications. Instead of formatting date strings directly in views, dates should be stored as 'datetime' objects (e.g., Carbon instances) in the model using Eloquent casts. This allows for consistent date manipulation and formatting in the display layer (Blade views) using Carbon's methods, ensuring reliability and maintainability. ```blade {{ Carbon::createFromFormat('Y-d-m H-i', $object->ordered_at)->toDateString() }} {{ Carbon::createFromFormat('Y-d-m H-i', $object->ordered_at)->format('m-d') }} ``` ```php // Model protected $casts = [ 'ordered_at' => 'datetime', ]; ``` ```blade // Blade view {{ $object->ordered_at->toDateString() }} {{ $object->ordered_at->format('m-d') }} ``` -------------------------------- ### Controller with Direct Database Query in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This controller method directly embeds complex database query logic, including eager loading and conditional filtering. This violates the 'Fat Models, Skinny Controllers' principle, making the controller less focused on handling HTTP requests and harder to test or reuse the query logic. ```PHP public function index() { $clients = Client::verified() ->with(['orders' => function ($q) { $q->where('created_at', '>', Carbon::today()->subWeek()); }]) ->get(); return view('index', ['clients' => $clients]); } ``` -------------------------------- ### Leveraging Convention for Table and Primary Key in Laravel Model (Good) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/burmese.md This snippet shows the recommended practice for a Laravel model, adhering to 'convention over configuration'. By omitting explicit $table and $primaryKey properties, Laravel automatically infers the table name ('customers') and primary key ('id') from the model's name ('Customer'). This reduces boilerplate and makes the code cleaner and more maintainable. The belongsToMany relationship also benefits from convention. ```PHP class Customer extends Model { public function roles(): BelongsToMany { return $this->belongsToMany(Role::class); } } ``` -------------------------------- ### Controller with Direct Business Logic in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This controller method directly handles file upload and movement logic, which is a specific business operation. This violates the Single Responsibility Principle for controllers, making them less focused on HTTP request handling and harder to test or reuse the file handling logic. ```PHP public function store(Request $request) { if ($request->hasFile('image')) { $request->file('image')->move(public_path('images') . 'temp'); } ... } ``` -------------------------------- ### Laravel Eloquent: Retrieving Single Column Value Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet illustrates using the `value('column')` Eloquent method to retrieve the value of a single column from the first result, offering a more direct and readable alternative to `->first()->name`. ```PHP ->first()->name ``` ```PHP ->value('name') ``` -------------------------------- ### Calculating Full Name with Mixed Logic - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `getFullNameAttribute` method violates the principle of 'methods doing one thing' by combining conditional logic for user roles and verification with the actual string concatenation for different name formats. It makes the method harder to read, test, and maintain. It depends on `auth()->user()` and user roles/verification status. ```PHP public function getFullNameAttribute(): string { if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } else { return $this->first_name[0] . '. ' . $this->last_name; } } ``` -------------------------------- ### Defining Custom Table and Primary Key in Laravel Model (Bad) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/burmese.md This snippet demonstrates a bad practice where a Laravel model explicitly defines the table name and primary key. This violates the 'convention over configuration' principle, as Laravel automatically infers these based on the model's name (e.g., 'Customer' implies 'customers' table and 'id' primary key). Explicitly setting them can lead to unnecessary boilerplate and potential inconsistencies. ```PHP class Customer extends Model { const CREATED_AT = 'created_at'; const UPDATED_AT = 'updated_at'; protected $table = 'Customer'; protected $primaryKey = 'customer_id'; public function roles(): BelongsToMany { return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); } } ``` -------------------------------- ### Laravel Eloquent: Ordering by Latest Specific Column Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates using the `latest('column')` Eloquent method to order results by a specific column in descending order, offering a more readable alternative to `orderBy('column', 'desc')`. ```PHP ->orderBy('age', 'desc') ``` ```PHP ->latest('age') ``` -------------------------------- ### Incorrect Full Name Attribute Implementation (PHP) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/italian.md This PHP method incorrectly combines multiple responsibilities: checking user roles/verification and formatting a full name. It violates the Single Responsibility Principle by handling conditional logic for different name formats within a single accessor, making it harder to test and maintain. ```PHP public function getFullNameAttribute(): string { if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } else { return $this->first_name[0] . '. ' . $this->last_name; } } ``` -------------------------------- ### Laravel Eloquent: Simple Where Clause Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates that the equality operator (`=`) is optional in Eloquent's `where()` method when performing a simple equality check, leading to more concise queries. ```PHP ->where('column', '=', 1) ``` ```PHP ->where('column', 1) ``` -------------------------------- ### Accessing Related Data in Blade (N+1 Problem) Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This Blade snippet iterates over all users and accesses each user's profile name directly within the loop. This causes an N+1 query problem, where one query fetches all users, and then N additional queries are executed to fetch each user's profile, leading to poor performance. ```blade @foreach (User::all() as $user) {{ $user->profile->name }} @endforeach ``` -------------------------------- ### Embedding PHP Data Directly in JavaScript Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet embeds PHP data directly into a JavaScript string using `json_encode`. This approach mixes concerns, makes JavaScript files less reusable, and can lead to issues with escaping and maintainability. ```javascript let article = `{{ json_encode($article) }}`; ``` -------------------------------- ### In-Controller Request Validation - PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This `store` method performs request validation directly within the controller. While functional, this approach clutters the controller with validation rules and makes them less reusable across different controller actions or tests. It depends on the `Request` object and its `validate` method. ```PHP public function store(Request $request) { $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', 'publish_at' => 'nullable|date', ]); ... } ``` -------------------------------- ### Violating Single Responsibility Principle in Laravel PHP Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/traditional-chinese.md This accessor method combines multiple responsibilities: checking user roles and verification status, and then formatting a full name based on that status. This violates the Single Responsibility Principle, making the method complex and less reusable. ```PHP public function getFullNameAttribute(): string { if (auth()->user() && auth()->user()->hasRole('client') && auth()->user()->isVerified()) { return 'Mr. ' . $this->first_name . ' ' . $this->middle_name . ' ' . $this->last_name; } else { return $this->first_name[0] . '. ' . $this->last_name; } } ``` -------------------------------- ### Passing PHP Data to JavaScript via HTML Attributes Source: https://github.com/alexeymezenin/laravel-best-practices/blob/master/README.md This snippet demonstrates passing PHP data to JavaScript by embedding it into HTML attributes using `@json($article)`. This separates concerns by keeping JavaScript in its own file and retrieving data from the DOM, improving maintainability and reusability. ```php Or