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!
CodePudding user response:
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
CodePudding user response:
Johns answer was absolutely correct, so get familiar with Laravel's Blade Templates and Components before down-voting.
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.php
file inresources\views\layouts
with 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.php
to view the new Layout
Route::get('/page1',function (){
return view('page1');
});
- Create
page1.blade.php
inresources\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.php
inresources\views
with 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}/page2
you'll seeI'm Page Two
with the search bar on top