Laravel: Is It Really Clean and Classy?

Share this article

Laravel is a clean and classy framework for PHP web development. Freeing you from spaghetti code, Laravel helps you create wonderful applications using simple, expressive syntax. Development should be a creative experience that you enjoy, not something that is painful. Enjoy the fresh air.
That’s the text which can be found on the Laravel homepage and, if we’d believe it, wouldn’t it be wonderful? Let’s test this claim by building a simple TODO application and see how much effort we have to put into it.

Migrations

First we’ll design the database. The application requires a rather simple schema, a single table with 5 columns to store an ID, title, description, and timestamps when the task was created and last updated. Laravel has a feature called migrations, which you might be familiar with already if you’ve used other frameworks like Ruby on Rails. Migrations are files which are used to update your database. As they are executed, they change your database schema in such a manner that you can easily apply updates to it. For our application, the migration looks something like this:
<?php
class Create_Todo_Table
{
public function up() {
Schema::table("todos", function($table) {
$table->create();
$table->increments("id");
$table->string("title", 20);
$table->text("description");
$table->timestamps();
});
}

public function down() {
Schema::drop("todos");
}
}
The up() method is called when the migration is being executed and the down() method is called when the migration is being reverted.

The Model

As Laravel is an MVC framework, we’ll need to create the model. Like with any other MVC framework you might know, the model is the component which is responsible for communicating with the database. Our table is simple, and so it only needs a simple model:
<?php
class Todo extends Eloquent
{
public static $timestamps = true;
}
The class name is “Todo” and Laravel will automatically associate this with the todos table in our database. Eloquent is an ORM class for models that Laravel uses, which provides a smooth way to work with database objects. The $timestamps property is set to true, which means that whenever a new entry is created or an existing entry is updated, the created_at and the updated_at fields will be updated accordingly.

The Controller

Now let’s create the controller. The controller is where all the business logic is located, and should therefore contain functionality to:
  • Retrieve all of the entries in the table to list them
  • Retrieve the information of a specific entry with a given id
  • Delete an entry with a given id
  • Compose a form to add a new entry
  • Add the new entry to the database and compose a message to confirm the addition
This gives us the following controller class with five methods, which we call actions. An action’s declaration must be preceded by the prefix “action_”.
<?php
class Todo_Controller extends Base_Controller
{
public function action_list() {
$todos = Todo::all();
return View::make("list")
->with("todos", $todos);
}

public function action_view($id) {
$todo = Todo::where_id($id)->first();
return View::make("view")
->with("todo", $todo);
}

public function action_delete($id) {
$todo = Todo::where_id($id)->first();
$todo->delete();
return View::make("deleted");
}

public function action_new() {
return View::make("add");
}

public function action_add() {
$todo = new Todo();
$todo->title = Input::get("title");
$todo->description = Input::get("description");
$todo->save();
return View::make("success");
}
}
The code is very straightforward. The first method action_list() will get all of the entries in the database. This is where Eloquent makes things easy, requiring only Todo::all() to fetch them. Then it returns a view with all of the entries from the database bound to the $todos variable. The other methods are also easy to read. They mostly exist to manipulate a database object and return a view with some data bound to it. The last method might be an exception; the action_add() will be called when submitting the form to add a new TODO entry. Input::get() is used to retrieve the submitted form values.

The View

Now we’ve come to the view. Laravel uses its own Blade templating engine which gives us clean and readable code. I will give an example of the first view, the list. With the make/with statement under the return of the view from action_list(), we put all the results of Todo::all() into $todos
. We can now use that in the view:
<h2>Todo list</h2>
<p>{{ HTML::link_to_action("todo@new", "Add new todo") }}</p>
<ul>
@foreach($todos as $todo)
<li>{{ HTML::link_to_action("todo@view", $todo->title, array($todo->id)) }} - {{ HTML::link_to_action("todo@delete", "Delete", array($todo->id)) }}</li>
@endforeach
</ul>
That’s all it takes! First we let Blade create a link to the controller’s action action_new(). Then we see the foreach statement which is quite similar to the one native to PHP. For every task we create a link to view the entry. The link text is the second parameter, $todo->title, and any parameters for the action should be provided next. We need the ID of the entry we want to view, which $todo->id provides. We also create a link to delete the task, again including the ID of the TODO as parameter.

Conclusion

So, that was that, and indeed it is simple to make an application using Laravel. The code is straightforward and easily readable. I hope this was useful to you, and you consider using Laravel with your next PHP application. See you next time! Image via Fotolia

Frequently Asked Questions about Laravel: Clean and Classy

What makes Laravel a clean and classy framework?

Laravel is considered a clean and classy framework due to its elegant syntax that is both easy to read and write. It follows the MVC (Model-View-Controller) architectural pattern, which separates the application into three interconnected components. This separation allows for efficient code organization, making it easier to maintain and understand. Laravel also comes with a variety of tools and features that streamline common tasks such as routing, security, and database management, further enhancing its cleanliness and classiness.

How does Laravel ensure code cleanliness?

Laravel ensures code cleanliness through its adherence to the MVC pattern, which promotes the separation of concerns. This means that each part of the code has a specific task, reducing dependencies and making the code more modular. Laravel also uses Object-Oriented Programming (OOP) principles, which encourage the use of classes and objects to create more organized and reusable code. Furthermore, Laravel provides a clean, simple API over the popular SwiftMailer library, allowing for clean and expressive syntax.

What are some clean code tactics in Laravel?

Some clean code tactics in Laravel include using Eloquent ORM for database operations, which provides a simple ActiveRecord implementation for working with your database. This allows you to write database queries in PHP, rather than SQL, leading to cleaner and more readable code. Another tactic is to use Laravel’s built-in validation rules to validate user input, which helps to maintain the integrity of your application’s data. Laravel’s Blade templating engine also allows you to create clean and elegant templates with its simple and powerful syntax.

How can I write clean code in Laravel?

Writing clean code in Laravel involves following good coding practices such as adhering to the DRY (Don’t Repeat Yourself) principle, which encourages reusability and reduces redundancy. You should also make use of Laravel’s features and tools, such as Eloquent ORM for database operations and Blade for templating. Additionally, you should write meaningful comments and use descriptive names for your variables, functions, and classes to make your code easier to understand.

What is the role of Classy Schema in Laravel?

Classy Schema is a tool that helps Laravel developers to create and manage database schemas in a clean and classy way. It provides a simple and expressive syntax for defining database tables and columns, making it easier to understand and maintain your database structure. Classy Schema also supports a variety of column types and indexes, allowing you to create complex database schemas with ease.

How does Laravel promote code elegance?

Laravel promotes code elegance through its expressive syntax and powerful features. Its MVC architecture and use of OOP principles allow for organized and modular code. Laravel’s Eloquent ORM provides a clean and simple API for database operations, while its Blade templating engine allows for clean and elegant templates. Laravel also provides a variety of tools and features that streamline common tasks, making your code more efficient and elegant.

How can I improve my Laravel coding skills?

Improving your Laravel coding skills involves practicing and learning more about the framework. You can do this by building projects, reading Laravel’s documentation, and following tutorials and guides. You should also learn about good coding practices such as the DRY principle and the use of meaningful comments and descriptive names. Additionally, you should familiarize yourself with Laravel’s features and tools, such as Eloquent ORM and Blade.

What are some common mistakes to avoid when coding in Laravel?

Some common mistakes to avoid when coding in Laravel include not following the MVC pattern, not using Eloquent ORM for database operations, and not making use of Laravel’s validation rules. These can lead to messy and inefficient code. Another common mistake is not writing meaningful comments or using descriptive names, which can make your code harder to understand. You should also avoid repeating code and instead strive for reusability.

How does Laravel compare to other PHP frameworks in terms of cleanliness and classiness?

Laravel stands out from other PHP frameworks in terms of cleanliness and classiness due to its elegant syntax and powerful features. Its adherence to the MVC pattern and use of OOP principles allow for clean and organized code. Laravel’s Eloquent ORM provides a clean and simple API for database operations, while its Blade templating engine allows for clean and elegant templates. Laravel also provides a variety of tools and features that streamline common tasks, making your code more efficient and elegant.

How can I keep my Laravel code clean as my application grows?

Keeping your Laravel code clean as your application grows involves following good coding practices and making use of Laravel’s features and tools. You should adhere to the MVC pattern and use Eloquent ORM for database operations. You should also use Laravel’s validation rules to maintain the integrity of your data. Additionally, you should write meaningful comments and use descriptive names for your variables, functions, and classes. As your application grows, you should also consider using Laravel’s service container for dependency injection, which can help to manage class dependencies and promote cleaner code.

SitePoint SponsorsSitePoint Sponsors
View Author
Intermediate
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week