Laravel for Beginners: The MVC pattern

Arlind Musliu Portrait
Arlind Musliu

January 3, 2024 · 8 min read

Laravel Blogpost Image

What is the MVC pattern in Laravel development?

The MVC pattern in Laravel is a software architectural pattern that separates an application into three interconnected components: Models, Views, and Controllers. This structure is designed to enhance organization and facilitate maintainability in web applications.

  1. Model: Represents the data structure, usually mirroring database tables. It handles data retrieval, storage, and manipulation. In Laravel, Eloquent ORM is used for database interactions within models.

  2. View: Responsible for presenting data to the user in a consumable format. It's where the application's user interface is generated and rendered with the data provided by the model.

  3. Controller: Acts as the intermediary between models and views. It processes incoming requests, interacts with the appropriate model to handle data, and sends the data to the view for presentation. Controllers in Laravel contain the business logic of the application and are responsible for responding to user input and performing interactions on the data model.

Note: Do not worry about coding for now, we will start coding in the following lessons. Focus on understanding these concepts as they will help you in your Laravel journey.

Why Use MVC in Laravel?

Using the MVC pattern in Laravel has a bunch of benefits:

  • Organization: MVC helps keep your code tidy and separated into logical pieces.

  • Efficiency: With MVC, developers can work on different parts of the app without stepping on each other's toes.

  • Maintainability: It's easier to update and maintain your code when it's well-organized.

  • Scalability: As your application grows, MVC makes it easier to expand.

What is a Model in Laravel?

A Model in Laravel represents the data-related logic of your application. It's where you define the properties and behaviors of the data you're working with. In database terms, a model typically corresponds to a table, and each instance of a model represents a row in that table.

For example, if you have a blog, you might have a Post model that represents the blog posts. Each Post would have attributes like title, content, and author.

Where to Find and How to Create a Model

In Laravel, models are usually stored in the app/Models directory. You can create a new model using the Artisan command-line tool that comes with Laravel.

php artisan make:model Post

This command creates a new Post model file in the app/Models directory. Here's what a basic model might look like:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    // Model content will go here
}

When you create a model in Laravel, you can also generate various related components such as migrations, seeders, and controllers:

php artisan make:model Post --migration

// or shorter

php artisan make:model Post -m

// add a migration, factory, seeder, and controller

php artisan make:model Post -mfsc

// generate a model with a migration, factory, seeder, policy, controller, and form requests

php artisan make:model Post --all

Model Relationships in Laravel

In any complex application, data is often interrelated. For example, a blog post may have many comments, a user might have a profile, or an order could be related to the customer who placed it. These connections between different types of data are what we call relationships. We explain these relationships in more detail in the next post, so no worries for now.

View: Multiple Frontend Options

The View is all about looks. It takes the data from the Model and turns it into web pages that people can interact with. When you're browsing a website, everything you see—the layout, the colors, the fonts—that's all the View's handiwork.

Laravel offers a variety of frontend options to cater to developers' preferences for crafting the user interface of their applications.

  • Blade Templates: Laravel has a built-in system called Blade that lets you write your web pages with simple code. It's easy to mix in data from your application, like showing a user's name or a list of blog posts.

  • JavaScript Frameworks: If you like using JavaScript to make your web pages interactive, Laravel works well with tools like Vue.js, React, and Angular. You can create a fancy, dynamic user experience with these.

  • Laravel Mix: This is a tool that helps you manage and mix your JavaScript and CSS files. It's like a blender for your web page's code, making sure everything combines nicely.

  • Starter Kits (Breeze & Jetstream): Laravel offers pre-made setups to get you started quickly. Breeze and Jetstream come with things like login pages and stylish layouts ready to go.

  • Tailwind CSS: When using starter kits, you'll get Tailwind CSS, which is like a set of building blocks for designing your site without writing lots of custom CSS.

  • Laravel Livewire: For those who want to make interactive pages without writing a lot of JavaScript, Livewire lets you do this right in your Blade templates. It's great for adding little interactive bits without the complexity.

With these options and the flexibility to integrate other tools and libraries, Laravel ensures that developers can choose the best frontend approach to suit their specific needs and workflow.

We've created Reactor for Laravel, an incredibly useful scaffolding package that incorporates React, Inertia.js, Radix UI, and developer tools such as Eslint, Prettier, and Husky to streamline our application development process. Feel free to use it if you prefer React as your frontend development choice.

What is a Controller in Laravel?

A Controller in Laravel acts as the command center for your application's interactions. It handles user input, processes it, and then responds, often by rendering a View with data provided by a Model. Controllers are where you put the logic that handles user requests, like submitting a form or clicking a link.

Where to Find and How to Create a Controller

Controllers in Laravel are stored in the app/Http/Controllers directory. You can create a new controller using Laravel's Artisan command-line tool with a command like this:

php artisan make:controller PostController

This command creates a new controller named PostController in your app/Http/Controllers directory. A newly generated controller might look something like this:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    // Controller methods will go here
}

How to Manipulate a Controller

Handling Requests

Controllers are responsible for handling requests to your application. Each public method in a controller can respond to a different route (URL). For example, you might have a method to show a list of blog posts:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function index()
		{
			$posts = Post::all();
			return view('posts.index', ['posts' => $posts]);
		}
}

This index method fetches all the posts using the Post model and then passes them to a view called posts.index, which would display them to the user.

Interacting with the Database

Laravel's Eloquent ORM provides an elegant and simple way to interact with your database. With Eloquent, each model you create is directly linked to a database table, and you can perform various operations without writing SQL queries.

To find a post with a specific id, you could use:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function index()
		{
			$post = Post::find(1);

			// or even better

			$post = Post::findOrFail(1);
		}
}

Creating and Saving Data

When you want to create a new post, you can simply create a new instance of the model, set its attributes, and then save it:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function store()
		{
			$post = new Post();
			$post->title = "My First Blog Post";
			$post->content = "Content of the blog post...";
			$post->save();
		}
}

Alternatively, you can use the create method, which accepts an array of attributes and creates a new model instance:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function store()
		{
			$post = Post::create([
				'title' => "My First Blog Post",
				'content' => "Content of the blog post...",
			]);
		}
}

Note: To use the create method, you must specify which attributes are mass-assignable in your model by setting the $fillable property. Open the Post model file and modify it like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
	protected $fillable = [
	   'title',
	   'content',
	];
}

Updating Data

To update a post, you fetch it from the database, change the attributes you want to update, and then call the save method:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function update()
		{
			$post = Post::find(1);
			$post->title = "Updated Title";
			$post->save();
		}
}

Deleting Data

To delete a post, you retrieve it and call the delete method:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function destroy()
		{
			$post = Post::find(1);
			$post->delete();
		}
}

Processing Form Input

Controllers also handle form submissions. For instance, when a new blog post is submitted through a form, you might have a store method to process it:

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
	 public function store(Request $request)
		{
			$validatedData = $request->validate([
				'title' => 'required|max:255',
				'content' => 'required',
			]);

			$post = Post::create($validatedData);

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

Here, the store method uses the $request object to access input data, validate it, and then create a new Post. Afterward, it redirects the user to the list of posts.

Resource Controllers

For standard CRUD (Create, Read, Update, Delete) operations, Laravel provides a way to quickly generate a controller with methods for each operation using the --resource flag:

php artisan make:controller PostController --resource

This generates a controller with methods like create, store, show, edit, update, and delete, corresponding to the typical actions you'd perform on a resource.

Invokable Controllers

Sometimes we need a controller that handles only one action. That's when we need to use invokable controllers. We can create them with the following command:

php artisan make:controller SomeController --invokable

Since the controller only contains a single action, you don't need to specify the method when defining the route. Laravel will automatically resolve and call the __invoke method. This is what an invokable controller looks like:

<?php

namespace App\Http\Controllers;

class SomeController extends Controller
{
    public function __invoke()
    {
        // some logic that we need to handle
    }
}

Conclusion

For beginners, understanding the MVC pattern is a big step towards mastering Laravel and web development in general. It helps you write clean, organized code, and Laravel provides all the tools you need to implement MVC effectively.

Upcoming Articles in the Series

  1. Laravel for Beginners: Model Relationships

  2. Laravel for Beginners: Laravel Migrations

  3. Laravel for Beginners: Laravel Seeders and Factories


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Laravel
Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!