Views, in an MVC pattern, contain the logic on how to present data to the user. In a web application, typically they are used to generate the HTML output that is sent back to users with each response. By default, views in Laravel are stored in the resources/views
directory.
A view can be called using the view
helper function:
view(string $path, array $data = [])
The first parameter of the helper is the path to a view file, and the second parameter is an optional array of data to pass to the view.
Therefore, to call the resources/views/example.php
, you would use:
view('example');
View files in subfolders within the resources/views
directory, such as resources/views/parts/header/navigation.php
, can be called using dot notation: view('parts.header.navigation');
Within a view file, such as resources/views/example.php
, you're free to include both HTML and PHP together:
<html>
<head>
<title>Hello world!</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Your name is: <?php echo $name; ?></p>
</body>
</html>
In the previous example (which doesn't use any Blade specific syntax), we output the $name
variable. To pass this value to our view, we would pass an array of values when calling the view helper:
view('example', ['name' => $name]);
or alternatively, use the compact()
helper. In this case, the string passed to compact() corresponds to the name of the variable we want to pass to the view.
view('example', compact('name'));
NAMING CONVENTION FOR BLADE VARIABLES
While sending data back to view. You can use underscore
for multi-words variable
but with -
laravel gives error.
Like this one will give error (notice hyphen ( - )
within the user-address
view('example',['user-address' => 'Some Address']);
The correct way of doing this will be
view('example', ['user_address' => 'Some Address']);