Building Routes, Controllers, and Views – Laravel Tutorial Part 2
Welcome back to our Laravel tutorial series! In Part 1, we set up our development environment and created our first Laravel project. Now, in Part 2, we’ll dive deeper into Laravel’s architecture and learn how to create routes, controllers, and views for our website. Let’s get started!
Tutorial Part 2: Building Routes, Controllers, and Views
Step 1: Define Routes
- Open the
routes/web.php
file in your Laravel project. - Define your routes using Laravel’s expressive routing syntax. For example:
Route::get('/', 'HomeController@index');
Step 2: Create Controllers
- Run the following command to generate a new controller named
HomeController
:
php artisan make:controller HomeController
- This command will create a new controller file in the
app/Http/Controllers
directory.
Step 3: Implement Controller Logic
- Open the
HomeController.php
file in yourapp/Http/Controllers
directory. - Implement the logic for your controller’s action methods. For example:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function index()
{
return view('welcome');
}
}
Step 4: Create Views
- In the
resources/views
directory, create a new Blade template file namedwelcome.blade.php
. - Add HTML and Blade syntax to define the content of your view. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome to My First Laravel Website</title>
</head>
<body>
<h1>Welcome to My First Laravel Website</h1>
<p>This is the homepage of our Laravel website. Feel free to explore!</p>
</body>
</html>
Step 5: Test Your Application
- Ensure your Laravel development server is still running.
- Open your web browser and navigate to http://localhost:8000/.
- You should see the homepage of your Laravel website, with the content defined in your
welcome.blade.php
view.
Conclusion: Great job! In Part 2 of our Laravel tutorial series, we learned how to define routes, create controllers, and build views for our website. We now have a basic homepage set up, and our application is starting to take shape. In the next part of the series, we’ll explore database migrations, models, and database interactions. Stay tuned for Part 3!