Laravel view is the presentation layer of laravel. Views are used to show the html and keep separate controller login from view logic. We can created nested views, dynamic views to show dynamic data, include another view in a view. It’s not practical to use a long html in controller or in a function so views are here. Views are stored in resources\views
folder and can be access using view('view_name',$array)
method.
Also read How to make a component in Laravel 8 ?
Here is the simple example
Create a route
Very first step is to create the route and call our view
<?php
use Illuminate\Support\Facades\Route;
Route::get('/hello', function(){
return view('hello');
});
Here, we used a anonymous function call the view using view
method and passed a parameter string hello
therefore we need to create a blade html file as well.
Create view
<body class="antialiased" style="text-align: center;">
This is a simple hello from readerstacks.com
</body>
Passing data to Laravel view
What if we wanted to pass data like some database model or a variable to our view then we can pass second parameter to our vies as below i
<?php
use Illuminate\Support\Facades\Route;
Route::get('/hello', function(){
return view('hello',['some_variable'=>1]);
});
and in view
<body class="antialiased" style="text-align: center;">
This is a simple hello {{$some_variable}} from readerstacks.com
</body>
Nested View
Nested views means nested folder for example resources/views/hello/world.blade.php then we can access it as below
return view('hello.world',['some_variable'=>1]);
How to check view exist or not in Laravel view?
Sometimes you need to check the existence of a view thus for this purpose we can use Laravel View class method exists()
Suppose we want to check a view existence of article.blade.php in folder resource/views/article then we can use it as below
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\View;
Route::get('/hello', function(){
if (View::exists('article.details')) {
return "View not found";
}
return view('hello',['some_variable'=>1]);
});
Sharing data between all views
Sometimes in our application we wanted to shared some specific data to all views like user details or sessions. So in this case we can use our View
facade’s share
method in our application service provider App\Providers\AppServiceProvider
. you need to define it in boot method of it.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
View::share('key', 'value');
}
}