Laravel 8 Tutorial - Views
In this video, we will learn about views in Laravel. A view is a presentation layer that the user can see, and it includes the HTML part, styling part, and all front-end development.
A view can be connected directly to a route or to a controller. Now, let's see how to create a view. To create a view, go to the resources directory, then open the views folder, and create a new file. Let's say the file name is user.blade.php.
Open this view file and add the HTML5 boilerplate by typing the ! sign and pressing tab. Change the title to "User" and add a message in the body part. I will type "User View" inside the h1 tag.
<h1>User View</h1>
Save the file. There are two ways to render a view: with a controller or directly with routing. Let's render the view through routing first. Switch to the routes folder and open the web.php file.
Write a route for the user view:
Route::get('/user',function (){
return view('user');
});
Save the file and go to the browser to check. Type localhost:8000/user in the browser, and you will see the user view.
Now, let's access the view using a controller. Create a controller by opening the command prompt and running the following command:
php artisan make:controller UserController
The UserController has been created. Open the UserController and create a method:
public function index()
{
return view('user');
}
Switch to the web.php file and modify the route:
Route::get('/user',[UserController::class,'index'])->name('user.index');
Check the browser again, and you will see that it's still working. If you want to pass some data, create a variable inside the index method and pass it to the view:
public function index()
{
$name = 'jenifer';
return view('user',compact('name'));
}
Go to the view file and display the name inside an h2 tag:
<h2>{{$name}}</h2>
Save the file and check it in the browser. You can also pass an array from the controller and render it on the view:
public function index()
{
$name = 'jenifer';
$users = array(
"name"=>"James Watson",
"email" => "james@gmail.com",
"phone"=>"7765498789"
);
return view('user',compact('name','users'));
}
Access the users array inside the user view:
{{$users->name}}
{{$users->email}}
{{$users->phone}}
Save the file and refresh the browser. You will see the result. This is how you can create a view and pass data from a controller to a view in Laravel 8.