The steps to create a new view in Laravel are as follows: 1. The view is stored in the resources/views directory and can be organized into subfolders according to functions; 2. Create a file with the extension .blade.php and add HTML content; 3. Return the view through a routing closure or controller, use the view() function and match the file name; 4. Dynamic data can be passed to the view through an array, compact() or with() method; 5. Use @extends and @section to implement layout inheritance to improve code reusability. Follow these steps to efficiently create and manage views.
Creating a new view in Laravel is straightforward, and it's one of the first things you'll do when building a web application with this framework. The main idea is to separate your logic from presentation by using Blade templates — Laravel's own templated engine.
Let's walk through how to create a new view step by step.
1. Understanding Where Views Are Stored
In Laravel, all views are stored inside the resources/views
directory. This is where Blade files live. Each .blade.php
file represents a single view.
If you're creating a simple homepage view, for example, you might place it directly in the views
folder:
resources/views/home.blade.php
For more complex applications, you can organize views into subfolders. For instance, if you're working on a blog section:
resources/views/blog/index.blade.php
This structure keeps things clean and easy to manage as your app grows.
2. Creating the Blade File
To create a new view:
- Navigate to the
resources/views
directory. - Create a new
.blade.php
file or a folder file if needed. - Add some basic HTML content to test it out.
Here's an example of what a basic Blade template might look like:
<!-- resources/views/welcome.blade.php --> <!DOCTYPE html> <html> <head> <title>Welcome</title> </head> <body> <h1>Welcome to My Site!</h1> </body> </html>
You don't need to use PHP tags unless you want to inject dynamic data — Blade makes that easy too (more on that below).
3. Returning the View from a Route or Controller
Now that you've created the view, you need to return it from a route or controller.
From a Route Closure:
Open routes/web.php
and define a route like this:
use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); });
The string 'welcome'
matches the filename welcome.blade.php
.
From a Controller:
If you're using a controller, make sure you import the View
facade or use the helper function view()
:
namespace App\Http\Controllers; use Illuminate\View\View; class HomeController extends Controller { public function index(): View { return view('welcome'); } }
Then link the controller method to a route:
use App\Http\Controllers\HomeController; Route::get('/', [HomeController::class, 'index']);
4. Passing Data to the View
Most of the time, you'll want to pass dynamic data to your views.
Let's say you want to pass a $name
variable:
In your route or controller:
return view('welcome', ['name' => 'John']);
In your Blade view ( welcome.blade.php
), you can display it like this:
<h1>Welcome, {{ $name }}!</h1>
Blade will automatically escape any HTML in {{ }}
, which helps prevent XSS attacks.
Other ways to pass data include:
- Using
compact()
to pass multiple variables at oncereturn view('profile', compact('user', 'posts'));
- Using the
with()
methodreturn view('profile')->with('user', $user);
5. Using Layouts and Sections (Optional but Powerful)
As your app grows, you'll probably want to reuse parts of your HTML (like headers and footers). Blade allows you to create layouts and extend them.
Create a layout file like this:
<!-- resources/views/layouts/app.blade.php --> <html> <head> <title>My Site</title> </head> <body> @yield('content') </body> </html>
Then create a child view that extends it:
<!-- resources/views/home.blade.php --> @extends('layouts.app') @section('content') <h1>Home Page</h1> @endsection
This way, you avoid repeating yourself and keep your code DRY.
So, creating a new view in Laravel really comes down to placing a .blade.php
file in the right location and returning it from a route or controller. Once you get the hang of Blade syntax and layout inheritance, building views become second nature.
Basically that's it.
The above is the detailed content of How do I create a new view in Laravel?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

In Laravel, routing is the entry point of the application that defines the response logic when a client requests a specific URI. The route maps the URL to the corresponding processing code, which usually contains HTTP methods, URIs, and actions (closures or controller methods). 1. Basic structure of route definition: bind requests using Route::verb('/uri',action); 2. Supports multiple HTTP verbs such as GET, POST, PUT, etc.; 3. Dynamic parameters can be defined through {param} and data can be passed; 4. Routes can be named to generate URLs or redirects; 5. Use grouping functions to uniformly add prefixes, middleware and other sharing settings; 6. Routing files are divided into web.php, ap according to their purpose

ToruntestsinLaraveleffectively,usethephpartisantestcommandwhichsimplifiesPHPUnitusage.1.Setupa.env.testingfileandconfigurephpunit.xmltouseatestdatabaselikeSQLite.2.Generatetestfilesusingphpartisanmake:test,using--unitforunittests.3.Writetestswithmeth

Artisan is a command line tool of Laravel to improve development efficiency. Its core functions include: 1. Generate code structures, such as controllers, models, etc., and automatically create files through make: controller and other commands; 2. Manage database migration and fill, use migrate to run migration, and db:seed to fill data; 3. Support custom commands, such as make:command creation command class to implement business logic encapsulation; 4. Provide debugging and environment management functions, such as key:generate to generate keys, and serve to start the development server. Proficiency in using Artisan can significantly improve Laravel development efficiency.

The main role of the controller in Laravel is to process HTTP requests and return responses to keep the code neat and maintainable. By concentrating the relevant request logic into a class, the controller makes the routing file simpler, such as putting user profile display, editing and deletion operations in different methods of UserController. The creation of a controller can be implemented through the Artisan command phpartisanmake:controllerUserController, while the resource controller is generated using the --resource option, covering methods for standard CRUD operations. Then you need to bind the controller in the route, such as Route::get('/user/{id

To start the Laravel development server, use the command phpartisanserve, which is provided at http://127.0.0.1:8000 by default. 1. Make sure that the terminal is located in the project root directory containing the artisan file. If it is not in the correct path, use cdyour-project-folder to switch; 2. Run the command and check for errors. If PHP is not installed, the port is occupied or file permissions are problematic, you can specify different ports such as phpartisanserve--port=8080; 3. Visit http://127.0.0.1:8000 in the browser to view the application homepage. If it cannot be loaded, please confirm the port number, firewall settings or try.

Laravelprovidesrobusttoolsforvalidatingformdata.1.Basicvalidationcanbedoneusingthevalidate()methodincontrollers,ensuringfieldsmeetcriterialikerequired,maxlength,oruniquevalues.2.Forcomplexscenarios,formrequestsencapsulatevalidationlogicintodedicatedc

CachinginLaravelsignificantlyimprovesapplicationperformancebyreducingdatabasequeriesandminimizingredundantprocessing.Tousecachingeffectively,followthesesteps:1.Useroutecachingforstaticrouteswithphpartisanroute:cache,idealforpublicpageslike/aboutbutno
