Laravel blade template specific code - php

Currently we are using the Laravel framework on several projects, but one issue we keep running into which i don't like is the following issue:
Lets say you have a Homepage and a Content page
HomepageController has all Homepage specific php code
ContentpageController has all Content specific php code
we have an app.blade.php that does
#yield('page')
HomepageController calls the view homepage.blade.php containing
#extends('app')
#section('page')
Some HTML part
#include('parts.top_5')
#endsection
ContentController calls the view content.blade.php containing
#extends('app')
#section('page')
Some different HTML part
#include('parts.top_5')
#endsection
Here you can see both pages include parts.top_5, the top 5 needs some specific variables to output the top5. Now the issue is we are currently copying the code for the top5 variables in both controllers or in grouped middleware but is there a better solution to generate some blade specific variables when the part is included? So a bit like running a controller function on loading the blade template?
I have been searching the internet but can't seem to find anyone with the same question. Hopefully someone can help me on this mindbreaking issue!

You can add this binding to AppServiceProvider
(or any custom ServiceProvider You want)
like this:
public function boot()
{
$view->composer('parts.top_5', function($view) {
$view->with('any_data' => 'You want');
})
}
This way any time Laravel will compose parts.top_5 view this closure method will be triggerd.
And in documentations it's here:
http://laravel.com/docs/5.0/views#view-composers

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>

PHP MVC understanding help (Laravel 5.3)

First, I want to say that it's the first time for me working
with a PHP Framework and MVC and I have not found all the answers to my problems yet. I'm using Laravel 5.3 at the moment.
Problem:
I have a website where a User can login and a few pages (I'm using Laravel Auth) and on a lot of pages I have a sidebar which is every time the same. Then I have on every page some content which is different (about, articles, ...). I heard that the most important thing is that you should never write code twice and there is the problem. On this sidebar there is a "service" which show content to the user but to show this I have an algorithm which needs the user data from the authenticated user and the Auth function is not available in Laravel 5.3 ServiceProvider or BaseController and was never meant to be.
My question now is how can I do that cleanly?
Some codes to understand it better:
Routes:
Route::get('/community/ranking', 'Pages\RankingController#getView');
Route::get('/community/advertising', 'Pages\AdvertisingController#getView');
Route::get('/logout', 'PagesController#doLogout');
Route::get('/home', 'Pages\HomeController#getView');
Then I have for every page an own controller which serves the content for this page (except of the sidebar - no solution yet).
HomeController:
<?php
namespace App\Http\Controllers\Pages;
use App\Http\Controllers\BaseController;
use Redis;
use App\Http\Requests;
use Request;
use Shoutbox;
use User;
class HomeController extends BaseController
{
function getView()
{
$shoutboxData = $this->getShoutboxData();
return view('pages.home', compact('shoutboxData'));
}
private function getShoutboxData()
{
$shoutbox = Shoutbox::orderBy('time', 'DESC')->skip(0)->take(15)->get();
if(count($shoutbox) > 0)
{
foreach($shoutbox as $entry)
{
$getUser = User::where('id', '=', $entry->user_id)->first();
$entry['username'] = $getUser->username;
$entry['look'] = $getUser->look;
$shoutboxData[] = $entry;
}
}
else
{
$shoutboxData = null;
}
return $shoutboxData;
}
public function systemMessage()
{
$redis = Redis::connection();
$redis->publish('chat.message', json_encode([
'msg' => 'System message',
'nickname' => 'System',
'system' => true,
]));
}
}
Now I serve the view in each, own controller and the content of this page (for example shoutbox, news) is also in that controller. (Not very clean in my opinion but didnt find any better way. Something I can improve here?).
I can serve the sidebar content on every Controller but this is not what I want. How can I do that? Am I using MVC right?
Thanks in advance!
Because you're using the Laravel Blade template system you can split your view logic out into separate blade files.
Your sidebar is common to every page so put this in your layout file (resources/views/layouts/app.blade.php) put the logic before
<div class="container" id="app">
#yield('content')
</div>
Now in your blade files for each individual page just extend the layout template you just created:
#extends('layouts.app')
#section('content')
<h1>page content goes here</h1>
#endsection
Now everyone of your blade files which extend the layouts.app will have the sidebar logic in them.
EDIT: With the extra information provided.... do as I said above but also create a view composer, you can find the full documentation here: https://laravel.com/docs/5.3/views#view-composers
Create a view composer for your main layout (or sidebar layout if you're going to be extending layouts instead) and pass your data within the view composer, the documentation gives good examples so just modify that for your own sidebar.

Laravel : Using controller in included view

I have a view that is rendered with its controller. The function that calls the view is linked in my routes. It works fine when directly accessing the route, but obviously my controller is not included when I include it in my template.
How do I use my controller when I include my view?
I'm on Laravel 3.
Right now I have my controller :
public function get_current()
{
// $sales = ...
return View::make('sale.current')->with('sales',$sales);
}
My route (which obv only work on GET /current) :
Route::get('current', 'sale#current');
My master view
#include('sale.current')
Then my sale.current view calls $sales
#foreach($sales as $sale)
Thanks!
So this is the case when you want to call some laravel controller action from view to render another partial view. Although you can find one or another hack around it. However, please note that laravel controllers are not meant for that.
When you encounter this scenario when you want to reuse the same view again but don't want to supply all necessary data again & again in multiple controller actions, it's the time you should explore the Laravel View Composers.
Here is the official documentation link : https://laravel.com/docs/master/views#view-composers
Here is the more detailed version of it :
https://scotch.io/tutorials/sharing-data-between-views-using-laravel-view-composers
This is the standard way of achieving it without any patch work.
Your question is still unclear but I can try to help you. I did a small example with the requirements you gave. I create a route to an action controller as follows:
Route::get('test', 'TestController#test');
In TestController I define the action test as follows:
public function test()
{
return View::make('test.home')->with('data', array('hello', 'world', '!'));
}
According to your asking, you defined a view who includes content from another view (layout) and in that layout you use the data passed for the action controller. I create the views as follows:
// home.blade.php
<h1>Message</h1>
#include('test.test')
and
// test.blade.php
<?php print_r($data); ?>
When I access to "test" I can see print_r output. I don't know if that is what you are doing, but in my case works fine.
I hope that can help you.

Categories