how to create dynamic pages in laravel | websolutioncode.com
how to create dynamic pages in laravel | websolutioncode.com

How to Create dynamic pages in laravel

Introduction:

Laravel is a powerful PHP framework known for its elegance and simplicity. One of its key features is the ability to easily create dynamic web pages. In this tutorial, we will explore how to Create Dynamic Pages in Laravel, explaining each step with practice code in easy-to-understand English.

Prerequisites:

Before we start, make sure you have Laravel installed on your machine. You can install it using Composer, the PHP package manager.

Step 1:

Setting Up Laravel Project Open your terminal and run the following command to create a new Laravel project:

composer create-project --prefer-dist laravel/laravel dynamic-pages

Navigate to the project folder:

cd dynamic-pages

Step 2:

Creating a Controller In Laravel, controllers handle the logic behind the dynamic pages. Let’s create a controller using the artisan command:

php artisan make:controller PagesController

This command generates a new controller file located at app/Http/Controllers/PagesController.php.

Step 3:

Defining Routes Open the web.php file in the routes folder. Define a route to map to our controller method:

use App\Http\Controllers\PagesController;

Route::get('/dynamic-page', [PagesController::class, 'dynamicPage']);

Step 4:

Implementing the Controller Open PagesController.php and add a method to handle the dynamic page:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PagesController extends Controller
{
    public function dynamicPage()
    {
        $data = [
            'title' => 'Dynamic Page',
            'content' => 'This is a dynamic page content.',
        ];

        return view('dynamic_page', $data);
    }
}

Step 5:

Creating a Blade View In Laravel, Blade is a templating engine. Create a new Blade view file named dynamic_page.blade.php in the resources/views folder:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ $title }}</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $content }}</p>
</body>
</html>

Step 6:

Testing the Dynamic Page Now, open your browser and navigate to http://localhost:8000/dynamic-page. You should see the dynamic page with the title and content we defined in the controller.

Conclusion:

Congratulations! You’ve successfully created a dynamic page in Laravel. This tutorial covered setting up a Laravel project, creating a controller, defining routes, implementing the controller logic, creating a Blade view, and testing the dynamic page. Feel free to explore more features of Laravel to enhance your dynamic web pages further.

Leave a Reply