Streamline Laravel Naming Conventions: 10 Steps to Clean and Maintainable Code

Mastering Laravel Naming Conventions: Clean and Maintainable Code

Topics: Laravel, Web Development, PHP Frameworks, Programming Best Practices, Software Engineering, Programming Tutorials, Laravel Tips, Web Development Guides, PHP Framework Practices


Introduction to Laravel Naming Conventions

Laravel’s naming conventions are essential for clean, maintainable, and scalable applications. By adhering to these standards across models, controllers, routes, migrations, views, and database schemas, developers can simplify collaboration and debugging. This guide provides a step-by-step hands-on explanation with examples for mastering these conventions.


1. Models

In Laravel, model names should be singular and in PascalCase. The convention is that the model class name should match the corresponding database table name in snake_case.

Example:

// Model: app/Models/BlogPost.php
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class BlogPost extends Model
{
    protected $table = 'blog_posts'; // Convention is to use snake_case table names
}
  • Model Class: BlogPost (singular, PascalCase).
  • Table Name: blog_posts (plural, snake_case).

Explanation:

  • The class BlogPost follows PascalCase, while the table it represents follows snake_case (blog_posts).
  • By default, Laravel assumes the plural form of the model name as the table name, so BlogPost maps to blog_posts.

2. Controllers

Controller names should be in PascalCase and end with Controller.

Example:

// Controller: app/Http/Controllers/BlogPostController.php
namespace AppHttpControllers;

use AppModelsBlogPost;
use IlluminateHttpRequest;

class BlogPostController extends Controller
{
    public function index()
    {
        $posts = BlogPost::all();
        return view('blog.index', compact('posts'));
    }

    public function show($id)
    {
        $post = BlogPost::findOrFail($id);
        return view('blog.show', compact('post'));
    }
}

Explanation:

  • The controller is named BlogPostController, which follows the convention of appending Controller to the model name in PascalCase.
  • Methods like index() and show() follow the camelCase convention for method names.

3. Routes

Laravel routes should be descriptive and use snake_case for parameter names. The route names should reflect the actions being performed.

Example:

// Routes: routes/web.php
use AppHttpControllersBlogPostController;

Route::get('/blog', [BlogPostController::class, 'index'])->name('blog.index');
Route::get('/blog/{id}', [BlogPostController::class, 'show'])->name('blog.show');

Explanation:

  • Routes are named in snake_case: blog.index, blog.show. This is particularly useful when generating URLs or redirects.
  • The {id} parameter is written in snake_case, consistent with the convention of writing parameters and variables in lower_case with underscores.

4. Migrations

Migration file names should be in the format YYYY_MM_DD_HHMMSS_create_table_name.php and follow snake_case for table names.

Example:

// Migration: database/migrations/2024_11_26_153000_create_blog_posts_table.php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

class CreateBlogPostsTable extends Migration
{
    public function up()
    {
        Schema::create('blog_posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('blog_posts');
    }
}

Explanation:

  • The migration file follows the format: 2024_11_26_153000_create_blog_posts_table.php.
  • The table name in the migration (blog_posts) is in snake_case, which aligns with Laravel’s default table name conventions.

5. Blade Views

View files in Laravel follow the snake_case convention and are typically stored in resources/views.

Example:

<!-- View: resources/views/blog/index.blade.php -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Blog Index</title>
</head>
<body>
    <h1>Blog Posts</h1>
    @foreach ($posts as $post)
        <h2>{{ $post->title }}</h2>
        <p>{{ $post->content }}</p>
    @endforeach
</body>
</html>

Explanation:

  • The view file index.blade.php is in snake_case.
  • The view is referenced using its path within the resources/views directory.

6. Database Column Naming

Column names in database tables should be in snake_case to maintain consistency across the application.

Example:

// Migration: Add columns to blog_posts table
public function up()
{
    Schema::table('blog_posts', function (Blueprint $table) {
        $table->string('author_name')->nullable();
        $table->timestamp('published_at')->nullable();
    });
}

Explanation:

  • Column names like author_name and published_at follow the snake_case convention.

7. Validation Rules

Validation rule names in controllers should be in camelCase.

Example:

// Controller method with validation
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'required|string|max:255',
        'content' => 'required|string',
    ]);

    BlogPost::create($validated);

    return redirect()->route('blog.index');
}

Explanation:

  • Validation rules ('title' => 'required|string|max:255') use snake_case for keys, as they reference form input names.
  • Validation logic itself follows camelCase for method and variable names.

Summary of Laravel Naming Conventions:

  1. Models: Singular, PascalCase (e.g., BlogPost).
  2. Controllers: PascalCase, ending with Controller (e.g., BlogPostController).
  3. Routes: Descriptive, snake_case (e.g., blog.index, blog.show).
  4. Migrations: YYYY_MM_DD_HHMMSS_create_table_name.php, snake_case for table names (e.g., blog_posts).
  5. Views: snake_case for file names (e.g., index.blade.php).
  6. Database Columns: snake_case (e.g., author_name, published_at).
  7. Validation Rules: camelCase for method names, snake_case for input keys.

Conclusion to Laravel Naming Conventions

Adopting Laravel’s naming conventions ensures consistency, readability, and ease of use in your applications. Whether you’re managing models, setting up migrations, or defining routes, following these best practices will streamline development, reduce errors, and foster a collaborative coding environment.


DoFollow

Stay Connected!

  • Connect with me on LinkedIn to discuss ideas or projects.
  • Check out my Portfolio for exciting projects.
  • Give my GitHub repositories a star ⭐ on GitHub if you find them useful!

Your support and feedback mean a lot! 😊

If you need any support regarding your website

If you like our blog, Please support us to improve

Buy Me a Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

RECENT POST
Leetcode Solutions

633. Sum of Square Numbers

Sum of Square Numbers Difficulty: Medium Topics: Math, Two Pointers, Binary Search Given a non-negative integer c, decide whether there’re

Leetcode Solutions

624. Maximum Distance in Arrays

Maximum Distance in Arrays Difficulty: Medium Topics: Array, Greedy You are given m arrays, where each array is sorted in

Leetcode Solutions

592. Fraction Addition and Subtraction

Fraction Addition and Subtraction Difficulty: Medium Topics: Math, String, Simulation Given a string expression representing an expression of fraction addition