Getting Started with Laravel: Basics of MVC and Controllers9 min read

Laravel stands out as a widely acclaimed PHP framework that adheres to the MVC architectural pattern. In this comprehensive Laravel guide tailored for beginners, I aim to demystify fundamental concepts within the framework. These include essential components like models, views, controllers, migrations, routes, and more. Through a hands-on example of posting product data to a database, we’ll delve into these core concepts. Ready to embark on your Laravel journey? Let’s dive in.

Setting Up Your Laravel Project

Let’s kick things off by creating and configuring a new Laravel project. If you haven’t done this before, fear not—I’ve got you covered with a step-by-step guide:

Install Laravel: Open your command prompt and execute the following command to install Laravel using Composer:

This process might take a little time, but soon you’ll have your Laravel project ready to roll. Once the installation is complete, open the project in your preferred code editor.

Database Setup: The next crucial step is creating a database for your project. If you’re unsure how to do this, refer to my detailed guide for assistance. Once your database is set up, navigate to the .env file in your Laravel project and configure the database connection settings:

  1. Input the relevant details for your database connection.

With these setup steps complete, your Laravel project is now linked to a database, and we’re all set to dive into the fundamentals of Laravel development in our beginner’s guide. Let the coding adventure begin!

Understanding Laravel Models

Let’s delve into the concept of Models in Laravel, a key component in the MVC architecture. The ‘M’ in MVC stands for Model, and in Laravel, a Model represents a database table. It’s important to note that the model name is singular, while its corresponding table in the database is plural. For instance, a ‘Product’ model would represent the ‘products’ table in the database.

Laravel simplifies database interactions through its eloquent ORM (Object-Relational Mapper). Eloquent provides a straightforward and efficient way to query data from the database using Models. This streamlines database operations, making them both easy and fast.

To create a Model in Laravel, we can utilize the Artisan command-line interface, like so:

Artisan commands enhance the development experience by providing a set of convenient commands.

Upon executing the above command, navigate to App\Models\Product.php in your project, and you’ll find the generated Model class. Here’s an example:

In this snippet, the ‘Product’ class extends Laravel’s ‘Model’ class and utilizes the ‘HasFactory’ trait. Traits, often used in languages with single inheritance, are like classes but serve the purpose of grouping functionality for reusability. Unlike classes, traits cannot be instantiated; instead, they are employed to organize and share functionalities efficiently across different classes.

Migrations in Laravel: Shaping Database Tables

In Laravel, the manual creation of database tables is replaced by migrations. Migrations allow us to define the schema of our database tables in a structured manner. To generate a migration, we can use the following Artisan command:

Within the database\migrations directory, you’ll discover the newly created migration file. This file contains two essential methods, up() and down(). When you execute the php artisan migrate command, the up() method will create the specified table in the database. Conversely, running php artisan migrate:rollback triggers the down() method, effectively reversing the migration.

Here’s an example of what the content of your migration file might look like:

In this example, the up() method specifies the structure of the ‘products’ table with columns such as ‘id’, ‘title’, ‘description’, ‘price’, and ‘timestamps’. The down() method, when called, will drop the ‘products’ table.

To create the tables in the database, run the php artisan migrate command. This seamlessly translates your defined schema into actual database tables.

Controllers in Laravel: Orchestrating Business Logic

In a Laravel project, a controller plays a pivotal role in organizing and managing the business logic related to handling specific requests. To encapsulate the logic associated with product-related requests, we’ll create a ProductController. Use the following Artisan command to generate the controller:

Navigate to your project’s app\Http\Controllers directory, and you’ll find the newly created ProductController.php file.

Note: For efficiency, you can combine the creation of a model, migration, and controller using the following command:

Or, using a shorthand:

Now, let’s add a createProduct() function to ProductController to return the view for creating a new product. Additionally, we’ll implement a storeProduct(Request $request) function to store the form request data into the database. Keep in mind that this is a basic example, and in a real-world scenario, you would want to implement request validation.

In the createProduct() function, we return the create.blade.php view file located inside a ‘product’ folder within the resources\views directory. Note that when returning views, you don’t need to include file extensions. If the view files are organized in folders within resources\views, specify the folder name followed by a dot and then the view file name (e.g., return view('product.create')).

The storeProduct(Request $request) function takes the form request as a parameter and stores it in the database using the Product model. The create method from Eloquent is utilized to store the request data. After the data is stored, the user is redirected back with a session message.

Views in Laravel: Crafting the Frontend

Views in Laravel define the frontend of your application, representing the HTML code responsible for rendering the web page design. When a user accesses a route in a web browser, the route either handles the request itself or delegates it to a controller function. Subsequently, a relevant view is returned along with any required data. Laravel incorporates the Blade template engine, which offers Blade directives to facilitate the handling of dynamic data in view files. Frontend files in Laravel are typically stored in the resources\views directory.

Here’s an example of a simple view file, create.blade.php:

In this example, the view file contains HTML markup for a form, utilizing Bootstrap classes for styling. Noteworthy elements include the use of Blade directives such as @if and {{ Session::get('message') }}. The double curly braces {{ ... }} indicate the embedding of dynamic data within the HTML. Blade directives provide a concise syntax for control structures, as demonstrated by @if (Session::has('message')). For a more in-depth understanding, refer to the Laravel Blade documentation.

Routes in Laravel: Navigating Requests

In Laravel, routes play a crucial role in defining the request URLs, and they aren’t tied to specific file names. Unlike core PHP, where URLs often map directly to file names, Laravel’s routing system is more user and search engine-friendly. Routes are typically specified in the routes\web.php file.

Here’s an example of how routes are defined in Laravel:

In this example, two custom routes are defined:

  1. The route '/' handles an HTTP GET request by returning the welcome.blade.php view directly.
  2. The route 'createproduct' also handles an HTTP GET request, but this time it forwards the request to the createProduct() function within the ProductController. This function returns the create.blade.php view.
  3. The route 'storeproduct' handles an HTTP POST request, forwarding it to the storeProduct(Request $request) function in the ProductController. This function receives the form request data through a POST method and stores it in the database.

To create a named route for the 'storeproduct' route, the ->name('storeproduct') method is used. Named routes are useful when generating URLs in your application.

These routes collectively define how your application responds to different HTTP requests, directing them to the appropriate controller functions or closures.

Leave a Comment