Trying to use service provider to set a variables throughout all views pages that #extends('layouts.app') but not working, first I show the codes below.
AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Using class based composers...
view()->composer('layouts.app', function($view){
$view->with('current_user', Auth::user());
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
When I visit the page that calls {{$current_user}}, it shows the following error
ErrorException in 5a5612347179ad88a6d4ebacc5d911a184c1b4ed.php line 14:
Undefined variable: current_user (View: C:\xampp\htdocs\soyegg\resources\views\shops\edit\showroom.blade.php)
Went through a several questions solved in the website and checked the followings but still failed:
1. AppServiceProvider is in config.app (default by Laravel 5.2)
2. php artisan clear-compiled
3. php artisan optimize
4. check whether there is compiled.php and try to clear it mannually but there is in neither storage/framework nor vendor.
Please help!
I think your ServiceProvider is working fine, you only need to change the way you passing data to the view. I've tested it myself and I can confirm that passing data to a view which later will be included with #extends() won't work. Instead you can use another methods:
view()->share('current_user', Auth::user());
Or using wildcard:
view()->composer('*', function ($view) {
$view->with('current_user', Auth::user());
});
// wildcard with prefix
view()->composer('prefix.*', function ($view) {
$view->with('current_user', Auth::user());
});
Related
I have a company parameter set in every route in my application. I am trying to send the variable for that company to each view for easy access.
In my AppServiceProvider.php I tried two things:
$company = App::make('request')->route()->getParameter('company');
view()->share('company', $company);
and also:
$company = Route::getCurrentRoute()->getParameter('company');
view()->share('company', $company);
But with both of them I get the error:
Call to a member function getParameter() on a non-object
How would I go about getting the parameter variable?
Edit:
I am doing it in the boot() function
Answer:
All I did was do the following in my register() function in AppServiceProvider:
view()->composer('*', function ($view) {
// all views will have access to current route
$view->with('company', \Route::getCurrentRoute()->getParameter('company'));
});
Current route is not yet known in AppServiceProvider as the application is still being bootstrapped here. If you want to access route parameters, you could use a view composer - see more details here https://laravel.com/docs/5.1/views#view-composers.
A quick example:
class AppServiceProvider extends ServiceProvider {
public function register()
{
view()->composer('*', function ($view) {
// all views will have access to current rout
$view->with('current_route', \Route::getCurrentRoute());
});
}
}
I just started my first Laravel project and try to combine Jetstream Authentification with Voyager Admin Panel.
First of all, I installed Jetstream on a fresh Laravel installation and it worked so far:
Afterwards, I tried to add Voyager to generate the CRUDs for my website and added a new user with
php artisan voyager:admin your#email.com --create
But whenever I tried to login through the url "../admin", I was redirected to "../dashboard" from Jetstream.
Even if I reentered "../admin" as URL, I was redirected. As long as I was logged in, I cannot enter the Voyager Backend.
So I guess it's some kind of routing / middleware issue, but I cannot find out which issue it is.
Within the web.php Routing file, there's only the basic stuff:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
});
Not sure if that's relevant, but my IDE recognizes Voyager:: as unknown class, even it works the same way on a different Laravel installation.
But from the look of it, I expected the Route::middleware() to redirect a logged in person which types the url "../dashboard" to the Dashboard view, but nothing more. Removing this Route also didnt help the problem, so I guess I was wrong.
But beside this, only the pure Voyager Routes are left, so I'm not sure where else I can look to solve this problem.
You can add custom responses on app/Http/Responses directory.
just make new responses called LoginResponse
then use this code
<?php
namespace App\Http\Responses;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class LoginResponse implements LoginResponseContract
{
/**
* #param $request
* #return mixed
*/
public function toResponse($request)
{
$home = auth()->user()->is_admin ? '/admin' : '/dashboard';
return redirect()->intended($home);
}
}
Then, bind your LoginResponse in FortifyServiceProvider
You can use this code
<?php
namespace App\Providers;
// ...
use App\Http\Responses\LoginResponse;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
class FortifyServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// ...
$this->app->singleton(LoginResponseContract::class, LoginResponse::class);
}
}
i know that it to late but for other users who had the same problem.
first i installed jetstream
int .env file APP_URL=http://localhost:8000
i installed voyager with dummy data
i added manualy in table user_roles this ligne ( the admin )
INSERT INTO `user_roles` (`user_id`, `role_id`) VALUES ('1', '1');
and it work
you can see this video i found in youtube i think it will help you .
https://www.youtube.com/watch?v=UDYZx5uIwmQ
I would like assistance with calling a global variable on Laravel app for specific pages or routes.
This is my current code which works on login
App\Providers\AppServiceProvider
public function boot()
{
view()->composer(['auth.login'], function ($view) {
$view->with('settings', AppSetting::where('id',1)->first());
});
}
This is the route for the login page
Route::get('/', function () {
return view('auth.login');
});
[Edit 1]
On the login page , I used this code bellow to get the app version
{{$settings->app_version}}
After digging a little I think a good solution might be caching your AppSetting Model.
Write the given code in App\Providers\RouteServiceProvider
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
parent::boot();
App::before(function($request) {
App::singleton('settings', function(){
return AppSetting::where('id',1)->first();
});
// If you use this line of code then it'll be available in any view
// as $settings but you may also use app('settings') as well
View::share('settings', app('settings'));
});
}
}
App::singleton will call once AppSetting::where('id',1)->first() and after one call your settings will be cached.
And you can use {{$settings->app_version}} in your view.
Reference: stackoverflow.com/a/25190686/7047493
I am building an app where each company have multiple users. And all users can upload documents/images/xls etc. I want to keep all company data in company separate folder. To complete this I am checking the company detail for every user and then upload data to company specific folder. Can I check company database once per user login and share user's company details to all controller and can easily access.
Use view composer in your AppServiceProvider
App\Providers\AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('*',function($view) {
if(auth()->user()) {
$comanyData = App\Company::where('user_id',auth()->user()->id);
$view->with('companyData', $companyData);
}
});
}
}
You can make the helper function to use in controllers or blades files.
Let’s create a helper!
Create a simple PHP file.
Create Helper.php inside the app directory or wherever directory you want.
<?php
/**
* get company data
*
*/
function companyData()
{
// Create logic of company data
// return company data
}
Autoload Composer
After we created our helper, Laravel won’t recognize our file so we need to register the helper file to our composer.json. Add File array inside the autoload section. It may look like this:
"autoload": {
"classmap": ["database"],
"psr-4": {"App\\": "app/"},
"files" : ["app/Helper.php"]
}
Then don’t forget to run
composer dumpautoload
Using helper function
Our helper is autoloaded now, so we should be able to use our helper immediately on different controllers. Just call our function in any class
$companyData = companyData();
or in blade view
{{ companyData() }}
Let me know if you are facing an issue.
Below is how to share a variable with your entire application via the AppServiceProvider, You can also do this inside of your base controller in the construct method.
File: App\Providers\AppServiceProvider.php
<?php
namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::share('key', 'value');
}
}
You can then access $key inside of any view.
I have the following problem, I want to share an array to all views in my project so I followed the documentation and it works fine, but I want to get the authenticated user in service provider boot function and it always return null ?
any suggestions ?
this is my code
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public $myusers;
public function boot()
{
$origLat=\Auth::user()->lat;
$origLon=\Auth::user()->lng;
$dist=5;
$lon1=$origLon-$dist/cos(deg2rad($origLat))*73.2044736;
$lon2=$origLon+$dist/cos(deg2rad($origLat));
$lat1=$origLat-($dist/73.2044763);
$lat2=$origLat+($dist/73.2044763);
$id=\Auth::user()->id;
$pictures=User::find($id)->pictures;
$this->myusers = DB::table('users')->select(
DB::raw("*,
3956 * 2 *
ASIN(SQRT( POWER(SIN(($origLat- lat)*pi()/180/2),2)
+COS($origLat*pi()/180 )*COS(lat*pi()/180)
*POWER(SIN(($origLon-lng)*pi()/180/2),2)))*1.609344
as distance"
))
->where('users.id', '!=', \Auth::user()->id)
->whereBetween('lng',[$lon1,$lon2])
->whereBetween('lat',[$lat1,$lat2])
->having("distance", "<", "$dist")
->orderBy("distance")
->get();
view()->share('myusers', $this->myusers);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
Unfortunately, at this point the Laravel application request lifecycle works in such a way that when the boot method of the App\Providers\AppServiceProvider class is executed the session is not yet initialised (since that's done in a middleware that is executed after the boot method).
Since the authentication systems needs the session in order to get the authenticated user, in your particular case you can't use view()->share() successfully there (although it's the recommended approach). Instead you can use an alternative approach by doing that in a middleware. Here are the steps that you can follow to make this work:
1. Create a middleware class, let's call it LoadUsers, by running this command:
php artisan make:middleware LoadUsers
2. That will generate a class in app/Http/Middleware/LoadUsers.php. Now you just need to move your code from the AppServiceProvider to the handle method of the middleware:
class LoadUsers
{
public function handle($request, Closure $next)
{
// Your code that shares the data for all views goes here
return $next($request);
}
}
3. Next you need to register the middleware with the App\Http\Kernel class. You can add it to the web group from $routeMiddleware if you want to apply the middleware to all routes that that use that or create your specific group or route middleware. So something like this if you want to add it to web:
protected $middlewareGroups = [
'web' => [
...
// Make sure to add this line is after the
// StartSession middleware in this list
\App\Http\Middleware\LoadUsers::class,
],
...
];
Now you should have the proper shared data for all your views that can depend on Auth::user().