View Composer not working Laravel - php

I have App\Http\NotificationComposer.php:
namespace App\Http\ViewComposers;
use Illuminate\View\View;
class NotificationComposer
{
public $notifications;
public function __construct(){
$this->notifications = json_decode(\Auth::user()->notifications, true);
}
public function compose (View $view)
{
dd($this->notifications);
$view->with('notifications');
}
}
I also have a App\Providers\ComposerServiceProvider.php:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
view()->composer(
'app',
'App\Http\ViewComposers\NotificationComposer'
);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
And in my config\app.php:
'providers' => [
...
App\Providers\ComposerServiceProvider::class,
...
],
];
I believe I have set up the view composer correctly, however everytime layouts\app.blade.php is loaded (the default bootstrap bar in laravel) it isn't rendering any notifications, even though there are some in the database, I have attempted to dd them as you can see in the view composer.
Does anyone have any ideas why this might be happening or what I haven't done properly?
Thanks,

Ok I've made a workaround instead. This wasn't registering for some reason so I place this inside of the AppServiceProivder.php
view()->composer(
'layouts.app', function ($view){
$view->with('notifications', json_decode(\Auth::user()->notifications, true));
});
It's not as clean but for something this small, I guess it's ok.

Related

Facades in laravel 8 Is perfectly working in controller file but i want to use on facade function in blade file not working

Facades in Laravel 8 Are perfectly working in the controller file but I want to use on facade function in the blade file not working
error:
Error Call to undefined method App\PaymentGateway\PaymentFacade::process() (View: D:\alpha\resources\views\admin\auth\register_coverage.blade.php)
**On Blade file, this is facade function **
{{ \Payment::process() }} //// this is not working
Controller file
public function registerStore(Request $request) {
dd(Payment::process()); ///// this is working
}
I want to know the solution to this problem.
Payment File
<?php
namespace App\PaymentGateway;
class Payment {
public static function process(){
return "testing";
}
}
PaymentFacade File
<?php
namespace App\PaymentGateway\Facades;
class PaymentFacade {
protected static function getFacadeAccessor(){
return 'payment';
}
}
PaymentServiceProvier File
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\PaymentGateway\Payment;
class PaymentServiceProvider extends ServiceProvider
{
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->app->bind('payment',function(){
return new Payment;
});
}
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
//
}
}
Config/app file
'providers' => [ App\Providers\PaymentServiceProvider::class,
],
'aliases' => [ 'Payment'=> App\PaymentGateway\Facades\PaymentFacade::class,
],
You should extend the base Facade class. Change App/PaymentGateway/Facades/PaymentFacade.php to
<?php
namespace App\PaymentGateway\Facades;
use Illuminate\Support\Facades\Facade;
class PaymentFacade extends Facade {
protected static function getFacadeAccessor(){
return 'payment';
}
}

Laravel 5.7: target is not instantiable while building

I know there are so many answer, but I cannot really solve this.
I did follow this answer (How to make a REST API first web application in Laravel) to create a Repository/Gateway Pattern on Laravel 5.7
I have also the "project" on github, if someone really kindly want test/clone/see : https://github.com/sineverba/domotic-panel/tree/development (development branch)
App\Interfaces\LanInterface
<?php
/**
* Interface for LAN models operation.
*/
namespace App\Interfaces;
interface LanInterface
{
public function getAll();
}
App\Providers\ServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
/**
* Solve the "Key too long" issue
*
* #see https://laravel-news.com/laravel-5-4-key-too-long-error
*/
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->register(RepositoryServiceProvider::class);
}
}
App\Providers\RepositoryServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(
'app\Interfaces\LanInterface', // Interface
'app\Repositories\LanRepository' // Eloquent
);
}
}
App\Gateways\LanGateway
<?php
/**
* The gateway talks with Repository
*/
namespace App\Gateways;
use App\Interfaces\LanInterface;
class LanGateway
{
protected $lan_interface;
public function __construct(LanInterface $lan_interface) {
$this->lan_interface = $lan_interface;
}
public function getAll()
{
return $this->lan_interface->getAll();
}
}
App\Repositories\LanRepository
<?php
/**
* Repository for LAN object.
* PRG paradigma, instead of "User"-like class Model
*/
namespace App\Repositories;
use App\Interfaces\LanInterface;
use Illuminate\Database\Eloquent\Model;
class LanRepository extends Model implements LanInterface
{
protected $table = "lans";
public function getAll()
{
return 'bla';
}
}
I did add also App\Providers\RepositoryServiceProvider::class, in providers section of config\app.php
This is finally the controller (I know that it is not complete):
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Gateways\LanGateway;
class LanController extends Controller
{
private $lan_gateway;
/**
* Use the middleware
*
* #return void
*/
public function __construct(LanGateway $lan_gateway)
{
$this->middleware('auth');
$this->lan_gateway = $lan_gateway;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$this->lan_gateway->getAll();
return view('v110.pages.lan');
}
}
And the error that I get is
Target [App\Interfaces\LanInterface] is not instantiable while building [App\Http\Controllers\LanController, App\Gateways\LanGateway].
I did try:
php artisan config:clear
php artisan clear-compiled
I think #nakov might be right about it being case-sensitive. I don't believe PHP itself cares about upper/lowercase namespaces, but the composer autoloader and the Laravel container use key->value array keys, which do have case-sensitive keys, to bind and retrieve classes from the container.
To ensure the names always match, try using the special ::class constant instead, like this:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Repositories\LanRepository;
use App\Interfaces\LanInterface;
class RepositoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(
LanInterface::class,
LanRepository::class
);
}
}
In my case i forgot to enlist the provider to confit/app.php that's why the error.
Clear the old boostrap/cache/compiled.php:
php artisan clear-compiled
Recreate boostrap/cache/compiled.php:
php artisan optimize

Laravel 5.6 Inject variable with Service Provider in a group of routes

I have a part of site that starts with specific prefix /manage.
Can I somehow like with AppServiceProvider view-composers inject a variable in all routes from that prefix?
I tried to do it by passing this variable to layout of all that routes. But then I met a problem. I use this variable in blade view of specific page, and it returns me variable not defined.
Then, I inspect laravel debugger and saw the order of loading of blade files. And it was :
1. Current page view
2. Layout view
3. Sidebars and other stuff
So, the fact that current page is loaded before layout, cause error of undefined variable.
So, how can I solve that ? Thanks.
Code from my Service provider :
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\CT;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
view()->composer(['website.implicare.ct.show', 'website.implicare.ct.petition.index', 'layouts.ct'], function($view) {
$ct = request()->ct;
$permissions = [];
foreach($ct->userPermissions(auth()->id()) as $userPermission) {
if($userPermission->pivot->ct_id == $ct->id) {
array_push($permissions, $userPermission->name);
}
}
$view->with('permissions', $permissions);
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
create ComposerServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public $theme = 'mytheme';
public function boot()
{
view()->composer($this->theme.'.includes.navbar', 'App\Http\ViewComposers\MenuComposer');
view()->composer($this->theme.'.includes.header', 'App\Http\ViewComposers\MenuComposer');
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}

ServiceProvider binded class not found

Case (L5.4)
Currently trying to write an api wrapper using the package development Laravel offers.
I got a ServiceProvider which binds the model (Niki::class)
class NikiServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
$this->publishes([
__DIR__ . '/config/niki.php' => config_path('niki.php'),
]);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
$this->app->bind('niki', function () {
return new Niki;
});
}
}
A Facade which registers the name of the component
class Facade extends \Illuminate\Support\Facades\Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
public static function getFacadeAccessor()
{
return 'niki';
}
}
And a model
class Niki extends Model
{
/**
* Config
*
* #var array
*/
public function __construct()
{
$this->config = config('niki')['api_key'];
}
public static function getHouses()
{
$response = $this->config;
return $response;
}
}
Above files are located in packages/prsc/niki/src and are being loaded using the psr-4 autoloading:
"psr-4": {
"App\\": "app/",
"PRSC\\Niki\\": "packages/prsc/niki/src/"
},
Error
So now my problem, the bind in the ServiceProvider returns a FatalError because of the file not being found.
FatalThrowableError in NikiServiceProvider.php line 37: Class
'PRSC\Niki' not found
I think it's just a namespace problem. I'm not sure I have all the clue about your namespaces, but here is something that should work (if I did not misunderstood):
Replace:
return new Niki;
By:
return new \PRSC\Niki\Niki;
If it does not work, please add your namespaces in each code snippet you pasted.

View composer not working properly in testing mode in Laravel 5.2

I've a view composer written like this
view()->composer('masterbox.partials.pipeline', function($view) {
// Some vars and code
});
In one of my view I do as follow
#include('masterbox.partials.pipeline', ['my_var' => 1])
When i'm trying it on my browser everything is fine, but when I run a simple test everything blows up ... After some debugging I found out the closure wasn't executed at all.
$this->visit('/connect/customer/subscribe')
->type($faker->firstName, 'first_name')
->type($faker->firstName, 'first_name')
->type($faker->lastName, 'last_name')
->type($faker->email, 'email')
->type($faker->phoneNumber, 'phone')
->type($password, 'password')
->type($password, 'password_confirmation')
->press("S'inscrire");
Note : It visits a page, fills the form and subscribe, then it redirects on the page with the #include and it returns a big error, part of it is
exception 'ErrorException' with message 'Undefined variable: my_var' in /Users/Loschcode/Google Drive/projects/my_project_lo/website/storage/framework/views/7e11f284c02bc38adc60b5f8a0545df65d7cf5ec.php:7
I'm afraid it an issue, it's a fresh Laravel 5.2 I downloaded a few days ago. Any guess ? Any method to debug this ? Thanks
Working solution
I ended up trying anything. My problem was my service provider organization.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
foreach (glob(app_path().'/Http/ViewComposers/*.php') as $filename){
require_once($filename);
}
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
If you have a similar organization and problem, replace the require_once by a simple require and everything will go fine.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
foreach (glob(app_path().'/Http/ViewComposers/*.php') as $filename){
require($filename);
}
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}

Categories