how to get current logged-in user details in laravel 5.2? - laravel

how do i get current logged in user details in laravel 5.2 ? I have done something to get the user name but it doesn't work properly.
Here is the code that gets the current logged-in user name
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Illuminate\Contracts\Auth\User;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\AuthController;
class UserProfileController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function current_user()
{
if(\Auth::check() && \Auth::user()->name) {
return 'hello';
return user()->name;
}
}
}
Here If i just return a ** return 'Hello'** in the function current_user , it works fine after checking the if condition, so i see there is no problem with if condition. But when i return user()->name it says
Call to undefined function App\Http\Controllers\user()

To access authorized user information use \Auth::user(). You probably just missing \Auth:: part, because You using correct syntax in condition.

You need to change your code a little bit.
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Illuminate\Contracts\Auth\User;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\AuthController;
class UserProfileController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function current_user()
{
if(\Auth::check() && \Auth::user()->name) {
return 'Hello '.\Auth::user()->name; //this line changed
}
}
}
After that you can get the current user name.
You want to return 2 values, that's not possible. When you return something your method will stop running. So that's why you didn't get the user name.
Hope this works!

Related

Policies Laravel not sending variable to controller

I'm new at Laravel, and I'm trying to make Policies that will prevent user that doesn't have id_level 1 which is admin to access InventarisController, but the InventarisPolicy doesn't send variable to InventarisController.
it's my Inventaris Policies
InventarisPolicy.php
<?php
namespace App\Policies;
use App\{User, Level};
use Illuminate\Auth\Access\HandlesAuthorization;
class InventarisPolicy
{
use HandlesAuthorization;
/**
* Create a new policy instance.
*
* #return void
*/
public function __construct()
{
//
}
public function inventaris_add(User $user)
{
$user->id_level == 1;
// dd($user);
// $user->id_level == 2;
}
}
it's my Inventaris Controller
InventarisController.php
<?php
namespace App\Http\Controllers;
use App\{Inventaris, DetailPinjamanView};
// use Illuminate\Http\Controllers\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
// use App\Http\Controllers\Auth\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class InventarisController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $viewpinjaman = DetailPinjamanView::all();
$this->authorize('inventaris_add', $user);
$inventaris = Inventaris::all();
return view('index', compact('inventaris'));
}

laravel policy not called

Does documention hides something, or there is something hidden?
created with
php artisan make:policy AdvertisementPolicy --model=Advertisement
class AdvertisementPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any advertisements.
*
* #param \App\User $user
* #return mixed
*/
public function viewAny(User $user)
{
return false;
}
public function view(User $user, Advertisement $advertisement)
{
return false;
}
model was created with cli too
namespace App;
class Advertisement extends Model
{
Registered through:
use App\Advertisement;
use App\Policies\AdvertisementPolicy;
class AuthServiceProvider extends ServiceProvider
{
protected $policies = [
Advertisement::class => AdvertisementPolicy::class,
Is here any additional steps to fulfill this policy registration with laravel 6?
There is no something hidden in documentation. You just don't read the documentation carefully.
Please take a look at the Authorizing Actions Using Policies section.
Your policy is never called, because you don't use it anywhere in your code. Atleast, if you need to run your policy for your controller resources, you need to write something like this:
<?php
namespace App\Http\Controllers;
use App\Advertisement;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AdvertisementController extends Controller
{
public function __construct()
{
$this->authorizeResource(Advertisement::class, 'advertisement');
}
}

Eloquent how to do something when delete or update operate on a special model

Most of my db table contain create_user_id and update_user_id
How can l update this two field automatic when l use save(), update(), insert(), createOrUpdate() and etc method.
For example, l execute this script:
$model = Model::find(1);
$model->model_f = 'update';
$model->save();
then this record's model_f updated, and update_user_id updated, too.
l know eloquent can manage update_time automatic and l have use it already. But l want to do something else when update or insert or delete
PS: l have a constant named USERID to remember current user's id
You could make use of Observers.
You can hook to the following events on your Model:
retrieved
creating
created
updating
updated
saving
saved
deleting
deleted
restoring
restored
Let me give you an example where we are trying to hook into the events emitted by the App/User model. You can change this to match your particular Model later on.
To create an observer, run the following command:
php artisan make:observer UserObserver --model=User
Then you can hook to specific events in your observer.
<?php
namespace App\Observers;
use App\User;
class UserObserver
{
/**
* Handle the User "saved" event.
*
* #param \App\User $user
* #return void
*/
public function saved(User $user)
{
//
}
/**
* Handle the User "created" event.
*
* #param \App\User $user
* #return void
*/
public function created(User $user)
{
//
}
/**
* Handle the User "updated" event.
*
* #param \App\User $user
* #return void
*/
public function updated(User $user)
{
//
}
}
Since, in your particular case, you want to hook into these 3 events, you can define the events above and perform additional operations to your model when those events are called.
Don't forget to register this observer in your AppServiceProvider.
<?php
namespace App\Providers;
use App\User;
use App\Observers\UserObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
User::observe(UserObserver::class);
}
/**
* Register the service provider.
*
* #return void
*/
public function register()
{
//
}
}
There is pretty simple way to automatically update the create_user_id and update_user_id
Step1:
Open you app folder and create the new file named as UserStampsTrait.php
Step:2
and paste the following code
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
trait UserStampsTrait
{
public static function boot()
{
parent::boot();
// first we tell the model what to do on a creating event
static::creating(function($modelName='')
{
$createdByColumnName = 'create_user_id ';
$modelName->$createdByColumnName = Auth::id();
});
// // then we tell the model what to do on an updating event
static::updating(function($modelName='')
{
$updatedByColumnName = 'update_user_id';
$modelName->$updatedByColumnName = Auth::id();
});
}
}
Thats it
Step:3
Open you model which needs to updated the corresponding models automatically
for Example it may be Post
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\UserStampsTrait;
class Post extends Model
{
use UserStampsTrait;
}
Thats it

Unable to access to Auth user info on Laravel

Im using Laravel 5.4 i have created the auth system guard using the laravel stuff, i have also created a role based registration form.
At this point all works so far, but for example i want to only certains pages to be available only for admin, so i have created a New User page to allow the admin create users.
My RegisteruserControoller:
namespace App\Http\Controllers;
use App\Proveedor;
use App\RubroProveedor;
use Illuminate\Http\Request;
use App\Http\Requests\StoreProveedor;
use App\Http\Requests\UpdateProveedor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Alert;
use Exception;
use Auth;
class RegisteruserController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('role:admin');
}
public function index(Request $request)
{
return view('usuarios.registeruser');
}
My problem here is if i use the middleware in construct im always being asked to login again and again, and i need to disable that but keep the guard to allow only admin user create new users.
Im not sure if im clear, im sorry my bad english.
I have created a Middleware called CheckRole:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
abort(401, 'This action is unauthorized.');
}
return $next($request);
}
}

Laravel5 default pagination

I have an error when simply put this
->paginate(15);
what is wrong with my code below
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Order;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator as Paginator;
class OrderController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$orders = Order::with('customer')->get()->paginate(5);
return view('order.index', compact('orders'));
}
}
appreciate if you someone can highlight to me what have I done wrong?
Remove the get() when you use paginate()
$orders = Order::with('customer')->paginate(15);

Resources