#6 What are Views in Laravel 5.6
Created by Imran Sayed Last updated January, 2020 English
Creating a View file
All view files should have an extension of .blade.php
Lets create a view file called about.blade.php inside projectname/resources/views
#projectname/resources/views/about.blade.php
Now lets create a route for this file inside projectname/routes/web.php file by defining the below method
Route::get('/about', function () {
return view('about'); // This will make the content of your view file about.blade.php available at localhost:8000/about
});
Its preferebale to keep your view files into separate folders so if you create the folder called myviews inside projectname/resources/views directory and place your about.blade.php file inside it, Then you will define the route inside projectname/routes/web.php like so
Route::get('/about', function () { // you can write /about or about it does not matter
return view('myviews/about'); // This will make the content of your view file about.blade.php available at localhost:8000/about
or
return view('myviews.about'); // This will make the content of your view file about.blade.php available at localhost:8000/about
});
You can also insert dynamic values in the url as $var and get that value inside the get method inside the route
Route::get('about/{id}/{name}', function ( $id, $name ) {
return This is the $id nd $name. // So if pass the $id in the url e.g. localhost:8000/about/2/page ...this will return 'This is 2 nd page'
});
Namespaces are a way of encapsulating items. For example, directories serve to group related files, and act as a namespace for the files within them.PHP Namespaces provide a way in which to group related classes, interfaces, functions and constants.
However its best practice to create a controller e.g. AboutController.php inside app/Http/controllers directory , return the view inside that controller and then provide route for that controller like so :
# inside app/Http/controllers/AboutController.php
// Here namespace means that this class belongs to Controllers
namespace App\Http\Controllers;
// use means we pull the Request and allow you to use request methods
use Illuminate\Http\Request;
class AboutController extends Controller {
public function about( Request $request ) { // ( Request $request ) will make the methods of Request class available inside $request var.
return view( 'about' );
}
}
# Inside routes/web.php
Route::get('about', 'AboutController');