I can get the Auth ID when i put it in any controller with
Auth::user()->id
But when i put it in AppServiceProvider.php , it returns `Trying to get property 'id' of non-object
i don't understand why ?
Eddit : I tried this but still not working
public function boot()
{
view()->composer('*', function ($view)
{
if (Auth::check())
{
$id=Auth::user()->id;
$idd=Person::where('user_id','=',$id)->get('photo');
$view->with('idd', $idd );
$view->with('id', $id );
}
});
}
Error :
Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given, called in
To get the currently authenticated user's ID, use
Auth::id();
Another case may be that there is not a current user, in which case Auth::user() is returning NULL. Wrap the code in a
if (Auth::check())
{
// Do stuff
}
to make sure there is a user logged in.
view()->composer('*', function($view)
{$view->with('user',auth()->user());
});
it's work for me
<?php
namespace Fitness\Providers;
use Illuminate\Http\Request;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot(Request $request)
{
view()->share('user', $request->user());
}
}
Related
I need the ID of the user who is logged in to get a photo in the profile table, here I am trying to use View but only in the index function that gets $profile, I want all files in the view to have $profile
public function index(){
$profil = Profil_user::where('user_id',$auth)->first();
View::share('profil', $profil);
return view('user.index');
}
I have also tried AppServiceProvider but I get an error in the form of a null value if I don't log in, is there a solution to my problem?
public function boot(){
$auth = Auth::user();
dd($auth);
}
exist several way to pass a variable to all views. I explain some ways.
1. use middleware for all routes that you need to pass variable to those:
create middleware (I named it RootMiddleware)
php artisan make:middleware RootMiddleware
go to app/Http/Middleware/RootMiddleware.php and do following example code:
public function handle($request, Closure $next) {
if(auth()->check()) {
$authUser = auth()->user();
$profil = Profil_user::where('user_id',$authUser->id)->first();
view()->share([
'profil', $profil
]);
}
return $next($request);
}
then must register this middleware in app/Http/Kernel.php and put this line 'root' => RootMiddleware::class, to protected $routeMiddleware array.
then use this middleware of routes or routes group, for example:
Route::group(['middleware' => 'root'], function (){
// your routes that need to $profil, of course it can be used for all routers(because in handle function in RootMiddleware you set if
});
or set for single root:
Route::get('/profile', 'ProfileController#profile')->name('profile')->middleware('RootMiddleware');
2. other way that you pass variable to all views with view composer
go to app/Http and create Composers folder and inside it create ProfileComposer.php, inside ProfileComposer.php like this:
<?php
namespace App\Http\View\Composers;
use Illuminate\View\View;
class ProfileComposer
{
public function __construct()
{
}
public function compose(View $view)
{
$profil = Profil_user::where('user_id', auth()->id)->first();
$view->with([
'profil' => $profil
]);
}
}
now it's time create your service provider class, I named it ComposerServiceProvider
write this command in terminal : php artisan make:provider ComposerServiceProvider
after get Provider created successfully. message go to config/app.php and register your provider with put this \App\Providers\ComposerServiceProvider::class to providers array.
now go to app/Providers/ComposerServiceProvider.php and do like following:
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
View::composer(
'*' , ProfileComposer::class // is better in your case use write your views that want to send $profil variable to those
);
/* for certain some view */
//View::composer(
// ['profile', 'dashboard'] , ProfileComposer::class
//);
/* for single view */
//View::composer(
// 'app.user.profile' , ProfileComposer::class
//);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
}
}
3. is possible that without create a service provider share your variable in AppServiceProvider, go to app/Provider/AppServiceProvider.php and do as follows:
// Using class based composers...
View::composer(
'profile', 'App\Http\View\Composers\ProfileComposer'
);
// Using Closure based composers...
View::composer('dashboard', function ($view) {
//
});
I hope be useful
you can use this
view()->composer('*', function($view)
{
if (Auth::check()) {
$view->with('currentUser', Auth::user());
}else {
$view->with('currentUser', null);
}
});
I made a piece of middleware that is responsible to check the permission a user has. I implemented a hasPermission function in my User model. But when I try to use it via the auth()->user I get the following error, why is this happening?
I implemented this method in my User Model
public function hasPermission($permission)
{
return in_array($this->permissions(), $permission);
}
And this is the middleware
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyPermission
{
public function handle($request, Closure $next, $permission)
{
if (auth()->check() && auth()->user()->hasPermission($permission)) {
return $next($request);
}
abort(401, 'Unauthorized');
}
}
It's because the user() method has a return type of \Illuminate\Contracts\Auth\Authenticatable|null which is an interface that your user class implements. This is because it might return different models based on the guard you're using but they all have to implement Authenticatable.
I'm not aware of an easy way to change this globally, but you could save the user in a variable and add a phpDoc block:
/** #var \App\User */
$user = auth()->user();
This should get picked up by intelephense and show the correct methods.
When I am trying to access Auth::user()->id;. its give me
Trying to get property 'id' of non-object
i am trying to access it in boot method for App\Providers
namespace App\Providers;
class AppServiceProvider extends ServiceProvider {
public function boot()
{
Schema::defaultStringLength(191);
$value = Auth::user()->id;
view()->composer('layouts.member', function ($view) use ($value) {
$view->with('value', $value);
});
}
}
I am going to make builder-bulder for query to use variable into master layouts blade.
You can't use Auth facade in the AppServiceProvider as the application is not fully booted yet.
Also, you will get the same error if there is no authenticated user. So it's better to wrap it in an optional method to avoid this error. In this case the value will be null.
However, you can use it inside the closure if you want that's what you want.
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('layouts.member', function ($view) {
$value = optional(Auth::user())->id;
$view->with('value', $value);
});
}
I am using Laravel5.5 and Module package. I have one student module and want to make this as a default for front-end, so committed code of the laravel's default routes/web.php
Here is my student's routes:
<?php
Route::group(['middleware' => 'web', 'namespace' => 'Modules\Student\Http\Controllers'], function() {
/** Frontend routes which does not require authentication
*
*/
Route::get('/', 'FrontEndController#index')->name('frontend.home');
Route::get('/program-search', 'FrontEndController#programs')->name('student.programs');
Route::get('/univeristy-search', 'FrontEndController#univerities')->name('student.universities');
});
And here is my controller code:
<?php
namespace Modules\Student\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Controllers\Controller;
use Modules\Admin\Http\Models\ProgramCategory;
use Modules\University\Http\Models\Program;
use Modules\Student\Http\Models\Student;
use Modules\University\Http\Models\University;
class FrontEndController extends Controller
{
/**
* Display a listing of the resource.
* #return Response
*/
public function index()
{
return view('student::index');
}
/**
* Show all programs
*/
public function programs(){
$categories = ProgramCategory::orderBy('catagory_name')
->where('status', '=', 'active');
$programs = Program::orderBy('program_name')
->where([
['status', '=', 'active']
]);
$programs->categories = $categories;
return view('student::program_list')
->withPrograms( $programs );
}
public function univerities()
{
return view('student::university_list');
}
}
only first route '/' is working. when I try to access '/program-search' and '/univeristy-search' it throws an error like "No hint path defined for [sutdent]. (View: /var/www/development/unigatenew/Modules/Student/Resources/views/university_list.blade.php)".
What is the wrong I am doing? can anybody help out this?
The mistake was including the same file name inside view. Renaming file name which was included solved the problem.
I used the scaffolding tools to generate my authentication code for my laravel project. I created a UserController to make a profile page which works great but when I try to make a function that can be used on Auth::user() i get an error Call to undefined method Illuminate\Database\Query\Builder::admin()
Why isn't the admin function accessible on the Auth::user()? Doesn't that extend my UserController? Or am I mixing it up with the model? Is the the model a good place to check if my user is an admin?
Here is my user controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;
class UserController extends Controller
{
/**
* Create a new user controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* #return View with user data
*/
public function index() {
$user = Auth::user();
return view('users.index', compact('user'));
}
/**
* #return bool
* Returns bool if the user is an admin.
*/
public function admin() {
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
}
and I am calling it on a different route controller function
public function index() {
return Auth::user()->admin();
}
I am fairly new to laravel and php so any critique is valuable and wanted!
You could add a function or attribute to you User model, I prefer attributes:
//User.php
class User extends Model{
protected $appends = ['is_admin'];
public function getIsAdminAttribute()
{
$user = Auth::user();
$authorized_users = [
'admin#test.com'
];
return array_key_exists($user->email, $authorized_users);
}
...
}
//Then in your view
Auth::user()->is_admin
No, Auth::user() does not extends any Controller. It represents the instance of the currently logged in/authenticated user. It will allow you retrieve other attributes of the use such as id, name etc Auth::user()->admin(); does not make any sense. Auth::user() has nothing to do with the UserController or any other controller.