How to Create Dynamic Pages in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hello,

In this article, I will demonstrate how to create dynamic pages in Laravel using a simple example of a Laravel dynamic page builder. This will help you grasp the concept of a Laravel page builder and provide you with a straightforward example of a Laravel page module.

In order to include essential information pages like "About Us," "Contact Us," "Terms & Conditions," "Terms & Privacy," and "Gallery," we are required to create individual routes, controller methods, and blade files for each page. Additionally, our clients may request additional pages with information. To simplify this process, we can develop a dynamic page creation module, allowing users to create and write content for their own pages. This eliminates the need for separate routes. In this post, I will demonstrate how to create dynamic pages in a Laravel application.

In this example, we will create pages table with id, title, slug and body column. Then we will crate CRUD for pages module. we will use CKEditor for content body so user can also upload image. Then we will create one route that will manage dynamic all the pages for front-end users.

So, let's follow the below step to done full example.

You can see the preview of page builder:

Step 1: Install Laravel 10 App

Let us begin the tutorial by installing a new laravel 10 application. if you have already created the project, then skip the following step.

composer create-project laravel/laravel example-app

Step 2: Database Configuration

In the second step, we will make a database configuration, we need to add the database name, MySQL username, and password. So let's open the .env file and fill in all details like as below:

.env

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=here your database name(blog)

DB_USERNAME=here database username(root)

DB_PASSWORD=here database password(root)

Step 3: Create Migration

Here, we will create a "pages" table using laravel migration. so let's use the following command to create a migration file.

php artisan make:migration create_pages_table --create=pages

After this command you will find one file in the following path "database/migrations" and you have to put below code in your migration file for creating the pages table.

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('pages', function (Blueprint $table) {

$table->id();

$table->string('title');

$table->string('slug');

$table->text('body');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('pages');

}

};

Now you have to run this migration by the following command:

php artisan migrate

Step 4: Create Controller and Model

In this step, now we will create two new controller PageController and FrontPageController. So run bellow command and create new controller. bellow controller for create resource controller.

php artisan make:controller PageController

php artisan make:controller FrontPageController

So, let's copy bellow code and put on PageController.php and FrontPageController.php file.

app/Http/Controllers/PageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Page;

use Illuminate\Http\RedirectResponse;

use Illuminate\Http\Response;

use Illuminate\View\View;

use Illuminate\Support\Str;

class PageController extends Controller

{

/**

* Display a listing of the resource.

*

* @return response()

*/

public function index(): View

{

$pages = Page::latest()->paginate(5);

return view('pages.index',compact('pages'))

->with('i', (request()->input('page', 1) - 1) * 5);

}

/**

* Show the form for creating a new resource.

*/

public function create(): View

{

return view('pages.create');

}

/**

* Store a newly created resource in storage.

*/

public function store(Request $request): RedirectResponse

{

$request->validate([

'title' => 'required',

'body' => 'required',

]);

$input = $request->all();

$input['slug'] = Str::slug($input['title']);

Page::create($input);

return redirect()->route('pages.index')

->with('success','Page created successfully.');

}

/**

* Show the form for editing the specified resource.

*/

public function edit(Page $page): View

{

return view('pages.edit',compact('page'));

}

/**

* Update the specified resource in storage.

*/

public function update(Request $request, Page $page): RedirectResponse

{

$request->validate([

'title' => 'required',

'body' => 'required'

]);

$input = $request->all();

$input['slug'] = Str::slug($input['title']);

$page->update($input);

return redirect()->route('pages.index')

->with('success','Page updated successfully');

}

/**

* Remove the specified resource from storage.

*/

public function destroy(Page $page): RedirectResponse

{

$page->delete();

return redirect()->route('pages.index')

->with('success','Page deleted successfully');

}

}

app/Http/Controllers/FrontPageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Page;

class FrontPageController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index($slug)

{

$pages = Page::all();

$page = Page::whereSlug($slug)->first();

return response()->view('page', compact('pages', 'page'));

}

}

Step 5: Add Resource Route

Here, we need to add resource route for pages crud application and need to add new page route for front user. so open your "routes/web.php" file and add following route.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PageController;

use App\Http\Controllers\FrontPageController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group that

| contains the "web" middleware group. Now create something great!

|

*/

Route::resource('pages', PageController::class);

Route::get('{slug}', [FrontPageController::class, 'index'])->name('page');

Step 6: Add Blade Files

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "pages" then create blade files of crud app. So finally you have to create following bellow blade file:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) page.blade.php

So let's just create following file and put bellow code.

resources/views/pages/layout.blade.php

<!DOCTYPE html>

<html>

<head>

<title>How to Create Dynamic Pages in Laravel - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>

.ck-editor__editable_inline {

min-height: 300px;

}

</style>

</head>

<body>

<div class="container">

@yield('content')

</div>

</body>

<script src="https://cdn.ckeditor.com/ckeditor5/34.2.0/classic/ckeditor.js"></script>

<script>

ClassicEditor

.create( document.querySelector( '#editor' ),{

ckfinder: {

uploadUrl: '{{route('ckeditor.upload').'?_token='.csrf_token()}}',

}

})

.catch( error => {

} );

</script>

</html>

resources/views/pages/index.blade.php

@extends('pages.layout')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>How to Create Dynamic Pages in Laravel - ItSolutionStuff.com</h2>

</div>

<div class="pull-right">

<a class="btn btn-success" href="{{ route('pages.create') }}"> Create New Page</a>

</div>

</div>

</div>

@if ($message = Session::get('success'))

<div class="alert alert-success">

<p>{{ $message }}</p>

</div>

@endif

<table class="table table-bordered">

<tr>

<th>No</th>

<th>Title</th>

<th>Slug</th>

<th width="280px">Action</th>

</tr>

@foreach ($pages as $page)

<tr>

<td>{{ ++$i }}</td>

<td>{{ $page->title }}</td>

<td>{{ $page->slug }}</td>

<td>

<form action="{{ route('pages.destroy',$page->id) }}" method="POST">

<a class="btn btn-info" href="{{ route('page',$page->slug) }}">Show</a>

<a class="btn btn-primary" href="{{ route('pages.edit',$page->id) }}">Edit</a>

@csrf

@method('DELETE')

<button type="submit" class="btn btn-danger">Delete</button>

</form>

</td>

</tr>

@endforeach

</table>

{!! $pages->links() !!}

@endsection

resources/views/pages/create.blade.php

@extends('pages.layout')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Add New Page</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="{{ route('pages.index') }}"> Back</a>

</div>

</div>

</div>

@if ($errors->any())

<div class="alert alert-danger">

<strong>Whoops!</strong> There were some problems with your input.<br><br>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

<form action="{{ route('pages.store') }}" method="POST" enctype="multipart/form-data">

@csrf

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

<input type="text" name="title" class="form-control" placeholder="Title">

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Body:</strong>

<textarea class="form-control" style="height:150px" id="editor" name="body" placeholder="Body"></textarea>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

</form>

@endsection

resources/views/pages/edit.blade.php

@extends('pages.layout')

@section('content')

<div class="row">

<div class="col-lg-12 margin-tb">

<div class="pull-left">

<h2>Edit Page</h2>

</div>

<div class="pull-right">

<a class="btn btn-primary" href="{{ route('pages.index') }}"> Back</a>

</div>

</div>

</div>

@if ($errors->any())

<div class="alert alert-danger">

<strong>Whoops!</strong> There were some problems with your input.<br><br>

<ul>

@foreach ($errors->all() as $error)

<li>{{ $error }}</li>

@endforeach

</ul>

</div>

@endif

<form action="{{ route('pages.update',$page->id) }}" method="POST" enctype="multipart/form-data">

@csrf

@method('PUT')

<div class="row">

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Title:</strong>

<input type="text" name="title" class="form-control" placeholder="Title" value="{{ $page->title }}">

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12">

<div class="form-group">

<strong>Body:</strong>

<textarea class="form-control" style="height:150px" id="editor" name="body" placeholder="Body">{{ $page->body }}</textarea>

</div>

</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">

<button type="submit" class="btn btn-primary">Submit</button>

</div>

</div>

</form>

@endsection

resources/views/page.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Laravel Dynamic Page Builder - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">

<div class="container-fluid">

<a class="navbar-brand" href="#">Laravel Pages(ItSolutionStuff.com)</a>

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">

<span class="navbar-toggler-icon"></span>

</button>

<div class="collapse navbar-collapse" id="navbarText">

<ul class="navbar-nav me-auto mb-2 mb-lg-0">

@foreach($pages as $link)

<li class="nav-item">

<a class="nav-link" href="{{ route('page', $link->slug) }}">{{ $link->title }}</a>

</li>

@endforeach

</ul>

</div>

</div>

</nav>

<div class="container">

<h1>{{ $page->title }}</h1>

{!! $page->body !!}

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/pages

After created new page, you can click on view button

http://localhost:8000/about-us

You will see layout as like bellow:

List Page:

Add Page:

Front Page:

I hope it can help you...

Tags :
Shares