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:
1 2 3 |
composer create-project laravel/laravel projectname |
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 2 3 4 5 6 7 8 9 10 |
# .env file DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=productapp DB_USERNAME=root DB_PASSWORD= |
- 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:
1 2 3 |
php artisan make:model Product |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; } |
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:
1 2 3 |
php artisan make:migration create_products_table --create=products |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('description'); $table->float('price'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('products'); } }; |
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:
1 2 3 |
php artisan make:controller ProductController |
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:
1 2 3 |
php artisan make:model Product --migration --controller |
Or, using a shorthand:
1 2 3 |
php artisan make:model shop -mc |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use App\Models\Product; use Illuminate\Http\Request; class ProductController extends Controller { public function createProduct() { return view('product.create'); } public function storeProduct(Request $request) { Product::create($request->all()); return redirect()->back()->with('message', 'Product added successfully'); } } |
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
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
<!doctype html> <html lang="en"> <head> <title>Title</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS v5.2.1 --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> </head> <body> <div class="container mt-4"> @if (Session::has('message')) <div class="alert alert-success" role="alert"> <strong>Alert</strong> {{ Session::get('message') }} </div> @endif <div class="row"> <div class="col-6"> <form action="{{ route('storeproduct') }}" method="post"> @csrf <div class="mb-3"> <label for="title" class="form-label">Title</label> <input type="text" name="title" id="title" class="form-control" placeholder="Enter product title"> </div> <div class="mb-3"> <label for="price" class="form-label">Price</label> <input type="number" name="price" id="price" class="form-control" placeholder="Enter product price"> </div> <div class="mb-3"> <label for="description" class="form-label">Description</label> <textarea class="form-control" name="description" id="description" rows="3" placeholder="Enter Product Description"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> </body> </html> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php use App\Http\Controllers\ProductController; use Illuminate\Support\Facades\Route; // Route handling request itself by accepting a closure Route::get('/', function () { return view('welcome'); }); // Route forwarding request to ProductController Route::get('createproduct', [ProductController::class, 'createProduct']); Route::post('storeproduct', [ProductController::class, 'storeProduct'])->name('storeproduct'); |
In this example, two custom routes are defined:
- The route
'/'
handles an HTTP GET request by returning thewelcome.blade.php
view directly. - The route
'createproduct'
also handles an HTTP GET request, but this time it forwards the request to thecreateProduct()
function within theProductController
. This function returns thecreate.blade.php
view. - The route
'storeproduct'
handles an HTTP POST request, forwarding it to thestoreProduct(Request $request)
function in theProductController
. 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.