'Which route is to write for same method on every page [closed]
Currenty developing a project in Laravel and want to now which route should I write when for example the search bar appears in the navigation bar on every page. It would be great if I get any advice here.
Thanks!
Solution 1:[1]
Johns answer was absolutely correct.
However I'll try to introduce you the basics in Laravel:
I assume you have a layouts.blade.php file in resources\views\layouts and its corresponding class in app\View\Componets\AppLayout.php
Or similar naming
- your
app.blade.phpfile inresources\views\layoutswith the following content:
app.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title of the document</title>
</head>
<body>
<!-- Your Content goes here -->
<div>
{{ $slot }}
</div>
</body>
</html>
AppLayout.php:
<?php
namespace App\View\Components;
use Illuminate\View\Component;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*
* @return \Illuminate\View\View
*/
public function render()
{
return view('layouts.app');
}
}
This is your base Layout for any pages on your website
- Create a route for your first page in your
routes\web.phpto view the new Layout
Route::get('/page1',function (){
return view('page1');
});
- Create
page1.blade.phpinresources\views
page1.blade.php:
<x-index-layout>
I'm Page One
</x-index-layout>
- Create a new component for your search bar
php artisan make:component SearchBar
edit resources/views/components/search-bar.blade.php with something like this:
<label for="search" title="Search">
<input type="search" placeholder="Search...">
</label>
- add the component to your
app.blade.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title of the document</title>
</head>
<body>
<!-- Search Bar -->
<x-search-bar/>
<!-- Your Content goes here -->
<div>
{{ $slot }}
</div>
</body>
</html>
This will add your search bar on any page as long as you use the <x-app-layout> directive on other pages:
run it in the browser with http://{your-url}/page1 you'll see I'm Page One with the search bar on top
- Create a new file
page2.blade.phpinresources\viewswith the following content
<x-app-layout>
I'm Page Two
</x-app-layout>
- Create its route:
Route::get('/page2',function (){
return view('page2');
});
- run it in the browser with
http://{your-url}/page2you'll seeI'm Page Twowith the search bar on top
Solution 2:[2]
The default rendering engine Blade uses layouts for all the components of the site that are generic, you could add your search bar there.
An additional step would be to make the search bar a component and render it in the layout
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | E_net4 - Krabbe mit Hüten |
| Solution 2 | John Zwarthoed |
