How do i load a method in a master blade template? - php

i am using laravel's blade template and i have a master template for all my pages. In the master template i have a top bar and a sidebar. I want to load something in the sidebar. But i don't know how do it in a simpler way. Now i am calling that method (which i want in to display in my sidebar) in every controller i have like this:
View::make()->with('data_to_load_in_sidebar',$data_to_load_in_sidebar)
How can i load this only once, not every time i generate a view?

This is what view composers are for, any view that is loaded will automatically have it's composer run alongside providing the view with any extra data it may require.
View::composer(array('partials.sidebar'), function($view)
{
$news = News::all();
$view->with('news', $news);
});
I typically put this in my routes.php file in both L3 and L4.
In the view views\partials\sidebar.blade.php you now always have access to the variable $news that will contain all models from the News collection.

I would share top bar & sidebar data in constructor (prefferably in some BaseController's contructor, that other controllers extends).
public function __construct()
{
// if needed, call parent's contructor method as well
parent::__construct()
$data_to_load_in_sidebar = loadDataForSidebar();
View::share('data_to_load_in_sidebar',$data_to_load_in_sidebar)
}

Related

laravel share view variables only if view extend specific layout

I have multiple layouts for the project.
So I'm calling a different layout base on the view requested.
I want to share a variables to a specific layout, and other variables for another one, and so on ..
i.e:
in layouts folder:
1- app.blade
2- base.blade
3- project1.blade
I want to share data to the layouts, without having to hard code these data every time I call a view in the controller:
if any view extend app.blade, then data1 is shared
if any view extend base.blade, then data2 is shared, and so on ..
is there an easy way to achieve this ?
You can use this function
In AppserviceProvider.php file boot function
view()->composer(['articles.index', 'articles.show', 'blog.*'], function ($view) {
$view->with('total', $total);
});

Adding information to a Layout without having to call it on every controller

I have a layout that is used when you are logged in. menu.blade.php.
Then I use it in blade files #extends('admin.layouts.menu')
I want to show some information in the layout, let's say the number of messages near the "message" link in the menu. I could easily do this by adding:
$message_count = Message::where("user_id", Auth::user()->id)->count();
and adding: <div>{{$message_count}}</div> to menu.blade.php
to every single controller and view where the layout is used, but this is clearly not a clean way to do it.
Is there a way to pass information to the view in a single step instead of having to do it in every single controller?
Use view composers.
View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location
Register the view composer within a service provider:
public function boot()
{
View::composer('menu', function ($view) {
$view->with('messagesCount', auth()->user()->messages->count())
});
}
Then each time when the menu view will be rendered, it will have $messagesCount variable with counted messages for an authenticated user.

Header Footer Controller in Laravel

I am working on Laravel for the first time
i have to make a Front End Menu Dynamic in Header and Footer [ list of categories will come from database ]. which controller I have to use for this.?
any common controller available in this framework to send data to header and footer.
When I receive the data in HomeController index Action its available for the home page only.
class HomeController {
public function index()
{
$categories = Category::get();
return view('home', compact('categories'));
}
}
Thanks.
This is a perfect case for View Composers:
View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.
You may attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method:
View::composer(['partials.header', 'partials.footer'], function ($view) {
$view->with('categories', [1, 2, 3]); // bind data to view
});
Now you could simply retrieve $categories within your view (blade template).
Tip: Common practice is to create a new service provider called ComposerServiceProvider and place the abovementioned composer logic in the boot() method.
I assume you are using the Header and Footer in a master layout file. In this case you need to send all header/footer info every request. Which would be silly so instead use View Composers:
Define them in your appServiceProvider in the boot() method
view()->composer('home', function($view) {
$view->with('categories', App\Category::all());
});
In my example i made 'home' the name of the view, since it is in your example. But i would make a master file called layout and include a header and footer partial. If you want categories inside your header you could make a view()->composer('layout.header') with only header data.
which controller I have to use for this.?
Any
any common controller available in this framework to send data to header and footer
No.
You control what is returned from the Controller to be the response. You can design layouts and break them up into sections and have views that extend them. If you setup a layout that has the header and footer and your views extend from it, you can use a View Composer to pass data to that layout when it is rendered so you don't have to do this every time you need to return a view yourself.
Laravel Docs 5.5 - Front End - Blade
Laravel Docs 5.5 - Views - View Composers
In case of this u can use components
https://laravel.com/docs/8.x/blade#components
php artisan make:component Header
View/Component.Header.php
public function render()
{
$category = [Waht you want];
return view('views.header', ['category'=>$category]);
}
Then include Header.php to your blade like this
views/front.blade.php
<html>
<body>
<x-header/> <!-- like this -->
#yield('content')
#include('footer')
<body>

How to use a layout statically in Laravel?

As an admin I can create pages (don't think I have to paste my adminpagescontroller here, because you understand the logic). What I'm getting stuck on, is selecting, but especially using the layout that will be used for the page.
i.e. I have three layouts:
page with left sidebar
page with right sidebar
page with full-width (no sidebars)
And i.e. I want to create a salespage or so, which uses the layouts "page with full-width". How can I call this in my view?
Now all my views begin with #extends('layouts.path.file') <--- I need that to be filled in by the database, if you know what I mean.
One way of doing it is to use a view composer to define the current layout to be used. View composers set variables that can be used by all your views ('*') or just some ('users.profile', 'admin.profile'), so this is an example of using a user specific layout:
View::composer('*', function($view)
{
$view->with('userLayout', Auth::check() ? Auth::user()->layout : 'main');
});
And in your view you just have to:
#extends('layouts.'.$userLayout);
If you just need to select a page on your controller, you can pass a layout to it:
return View::make('myview')->with('layout', 'front.main');
And use it in your view:
#extends('layouts.'.$layout);
And if you have it on a table, you can just pass it on:
$layout = Pages::first()->layout;
return View::make('myview')->with('layout', $layout);
Or do the same in your composer
View::composer('*', function($view)
{
$layout = Pages::first()->layout;
$view->with('layout', $layout);
});
A lot of people like to set the layout in controller too, so you could in your controller do:
public function showProfile()
{
$this->layout = Pages::first()->layout;
$this->layout->content = View::make('user.profile');
}
And your views doesn't have to #extend a layout anymore, because you are already telling them which layout to use.

Making a controller for home page

Can you tell me how to use a controller for home page because i'm trying to put a model's data in home.ctp (homepage view) with
<?php $this->user->find() ?>but it returns
Notice (8): Undefined property:
View::$user [APP\views\pages\home.ctp,
line 1]
You should check out the cookbook; it has some solid CakePHP tutorials, at http://book.cakephp.org/
You haven't really provided alot of information, but my guess is your Controller uses a model 'User', and you're putting $this->user->find() in your view, when it should be in your controller. In your controller's action you'll want/need to do something like this...
Users_Controller extends AppController {
function index() {
$arrayOfUsers = $this->User->find(...);
$this->set('users', $arrayOfUsers);
}
}
You can then - in your View - access 'users' like so:
pre($users);
... since you used the Controller method set() to send a variable $users to the view.
All you really need to do is create a new controller if that's the direction you want to go. If this is the only statement you have that requires data access, it might be worth faking it in only this method of the PagesController. For example, one of my projects' homepages is 99% static save for a list of featured events. Rather than move everything out to a new controller or even loading my Event model for the entire PagesController (where it's not needed), I just applied this solution in PagesController::home():
$attractions = ClassRegistry::init ( 'Attraction' )->featured ( 10 );
Works great. If your page is more dynamic than mine, though, it may well be worth routing your homepage through a different controller (one that is more closely related to the data being displayed).
The default controller for the home page i.e home.ctp view, is located in /cake/libs/controller/pages_controller.php. This controller can be overriden by placing a copy in the controllers directory of your application as /app/controllers/pages_controller.php. You can then modify that controller as deem fit i.e. use models, inject variables to be used in the home page etc

Categories