I am new to laravel. I am using multi authentication in my application. User and Admin are 2 type of user in my application. Iam developing change password for admin after logged in to application through admin's profile page. now I want to get logged in admin user detail so that i have use below code in my controller
if (Auth::guard('admin')->check()) {
$user = Auth::id();
echo '<pre>';
dd($user);
exit;
}
I have also add following code in controller
use App\Http\Controllers\Adminauth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Admin;
use Session;
use DB;
use App\Http\Controllers\Controller;
use Auth;
In route.php i have write following code
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
Route::auth();
Route::get('admin/profile/change_password', 'Admin\AdminController#change_password');
});
But i am not able to get admin user detail. can anyone help me to solve this problem.
Try this
public function __construct() {
$this->middleware('auth:admin');
$this->middleware(function ($request, $next) {
$user = $this->user = Auth::user();
dd($user);
});
}
In routes
Route::get('/', function () {
//return view('welcome');
return view('auth.login');
});
Auth::user() is working only under auth middleware. You may call auth middleware on controller or call it on routes, but not on both.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class YourController extends Controller
{
public function __construct()
{
$this->middleware('auth')
}
public function yourFunction(Request $request)
{
$user = \Auth::user();
dd($user);
}
}
<?php
Route::get('your-uri', function () {
$user = \Auth::user();
dd($user);
})->middleware('auth');
Related
This is the error I'm receiving when I try to load my index page
Too few arguments to function App\Http\Middleware\HasPermission::handle(), 2 passed in /app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 180 and exactly 3 expected
I'm using Spatie's Roles and Permissions Package, and have created a custom middleware HasPermission, to check if the user has the permissions to access and utilise the page they are trying to view.
This is the middleware
namespace App\Http\Middleware;
use Closure;
use Spatie\Permission\Models\Permission;
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
foreach($permissions_array as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
}
The controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Illuminate\Support\Arr;
use App\Http\Middleware\HasPermission;
class UserController extends Controller
{
public function __construct() {
$this->middleware('permission:usermgmt.users|usermgmt.users.create|usermgmt.users.edit|users.delete', ['only' => ['index','store']]);
$this->middleware('permission:usermgmt.users.create', ['only' => ['create','store']]);
$this->middleware('permission:usermgmt.users.edit', ['only' => ['edit','update']]);
$this->middleware('permission:users.delete', ['only' => ['destroy']]);
}
And my routes
Route::middleware('HasPermission')->group(function() {
Route::get('/usermgmt/users', [App\Http\Controllers\UserController::class, 'index'])->name('usermgmt.users');
Route::resource('users', UserController::class);
Route::get('add-user', [App\Http\Controllers\UserController::class, 'create'])->name('usermgmt.users.create');
Route::delete('users/{user}',[App\Http\Controllers\UserController::class, 'destroy'])->name('users.destroy');
Route::get('users/{user}/edit', [App\Http\Controllers\UserController::class, 'edit'])->name('usermgmt.users.edit');
});
I have added the HasPermission middleware class to the Kernel.php, but am struggling to understand why I am receiving that error.
Any help would be appreciated, cheers.
I tried initially removing the Route Middleware Group and instead trying to do everything in the controller, and tried something like the below
$this->middleware(HasPermission::class, ['usermgmt.users','usermgmt.users.create','usermgmt.users.edit','users.delete'], ['only' => ['index','store']]);
But this would give me the same error as before.
Did you try this way:
public function handle(Request $request, Closure $next, ...$permissions)
{
foreach($permissions as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
The in your controller, change the syntax:
$this->middleware('permission:usermgmt.users,usermgmt.users.create,usermgmt.users.edit,users.delete', ['only' => ['index','store']]);
I want my /dashboard page to be a different panel in 2 different user types. And return to home screen if not logged in. I created 2 middlewares to check if logged in user is "employer" or "employee". Whatever I do, I can't seem to make it work, it's been 2 days. I created middlewares and routes by following some very sketchy tutorials, it may hurt your eyes, be aware.
My route:
Route::get('/dashboard', function () {
return view('welcome');
})->name('welcome');
Route::prefix('admin')->middleware([\App\Http\Middleware\isEmployer::class])->group( function () {
Route::get("/dashboard", function (){
return view("employer.dashboard");
})->name("dashboard");
});
Route::prefix('store')->middleware([\App\Http\Middleware\isEmployee::class])->group( function(){
Route::get("/dashboard", function (){
return view("employee.dashboard");
})->name("dashboard");
});
isEmployee middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class isEmployee
{
public function handle(Request $request, Closure $next)
{
if(Auth::user())
{
if (Auth::user()->role == "employee")
{
return $next($request);
}
}
return response()->view('welcome');
}
}
isEmployer middleware :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class isEmployer
{
public function handle(Request $request, Closure $next)
{
if(Auth::user())
{
if (Auth::user()->role == "employer")
{
return $next($request);
}
}
return response()->view('welcome');
}
}
What I want to achieve is:
if not logged in : return welcome view
if logged in as employer : return employer.dashboard view
if logged in as employee : return employee.dashboard view
Let's start from some refactoring:
Make your routes/web.php a bit more readable:
Route::view('/dashboard', 'welcome')->name('welcome');
Route::prefix('admin')->name('admin.')->middleware('role:employer')->group(function() {
Route::view('/dashboard', 'employer.dashboard')->name("dashboard");
});
Route::prefix('store')->name('store.')->middleware('role:employee')->group(function() {
Route::view('/dashboard', 'employee.dashboard')->name("dashboard");
});
Now let's create a middleware that will check not only for one role, but for any role you give as a parameter:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HasRole
{
public function handle(Request $request, Closure $next, string $role)
{
if (Auth::user()?->role != $role) {
return redirect()->route('welcome');
}
return $next($request);
}
}
Now, create an alias in your app/Http/Kernel.php so you could use it like i wrote it in routes file role:<role_here>:
protected $routeMiddleware = [
// ...
'role' => \App\Http\Middleware\HasRole::class,
];
Now for your question - how to use multiple middlewares for one route. It is simple:
$route->middleware(['middleware1', 'middleware2']);
You may attach them to groups or single routes:
Route::prefix('some_group')->middleware(['middleware1', 'middleware2'])->group(function() {
Route::view("some.view")->middleware('middleware3')->name("some.view");
});
You can read more info about Laravel's middlewares here, and understand what responsibility chain is (pattern which middleware implements) under the hood. Also take a look at SOLID principles, mainly at DRY one. Have a good day =)
i am working on API. I want to create login api. i have created UsersController in API folder it in controllers. when i run in postman i shows an error
Illuminate\Contracts\Container\BindingResolutionException: Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController] does not exist. in file F:\University_Data\xamp\htdocs\stylooworld\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 835`
I don't now why its duplicated the routing path Target class [App\Http\Controllers\App\Http\Controllers\API\UsersController]
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
UsersController.php
<?php
namespace App\Http\Controllers\API;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Controllers\UserController;
class UsersController extends Controller
{
//
public function loginUser(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
echo "<pre>";
print_r($data);
die;
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
// check email is activated or not (Only Work Online Server)
/* $userStatus = User::where('email', $data['email'])->first();
if ($userStatus->status == 0) {
Auth::logout();
$message = "Your account is not activated yet! Please confirm your email to activate!";
Session::flash('error_message', $message);
return redirect()->back();
}*/
//update user cart with user id
if (!empty(Session::get('session_id'))) {
$user_id = Auth::user()->id;
$session_id = Session::get('session_id');
Cart::where('session_id', $session_id)->update(['user_id' => $user_id]);
}
return redirect('/');
} else {
$message = "Invalid Username or Password";
Session::flash('error_message', $message);
return redirect()->back();
}
}
}
}
I don't know why this happen?
Update the routes.
For details please check (ref link) https://laravel.com/docs/8.x/upgrade and https://laravel.com/docs/8.x/releases#routing-namespace-updates
Use like this
api.php
If not working
Route::namespace('App\Http\Controllers\API')->group(function () {
Route::post('login', 'UsersController#loginUser');
});
Then Use like this
use App\Http\Controllers\API\UsersController;
Route::post('login', [UsersController::class, 'loginUser']);
import method Request
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
on click (import method) always ready.
are you ok.
I am Automatically logout after refreshing the page in laravel 6. Everything is working fine but I am successfully logged in but when I refresh the page automatically logged out. I am using a socialite package to login to my app. I also increase the session lifetime to 180 in config/session.php file but still didn't work...
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use App\Models\Constant_model;
use App\SocialProvider;
use App\User;
use Socialite;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = RouteServiceProvider::HOME;
// public function __construct()
// {
// $this->middleware('guest')->except('logout');
// }
public function redirectToProvider($provider)
{
return Socialite::driver($provider)->redirect();
}
public function handleProviderCallback($provider)
{
$social_user = Socialite::driver($provider)->user();
$authuser = $this->findOrCreateUser($social_user,$provider);
Auth::login($authuser,true);
return redirect('/');
}
public function findOrCreateUser($social_user,$provider){
$authuser = SocialProvider::where('provider_id', $social_user->id)->first();
if(!$authuser){
$user = User::firstOrCreate(
['email'=> $social_user->getEmail()],
['ip_address'=> '127.0.0.1'],
['user_name'=> $social_user->getName()],
['name'=> $social_user->getName()],
['picture'=> $social_user->getAvatar()],
['password'=> 'sfdsfsdffsfsfs'],
);
$user->socialProviders()->create(
['provider_id'=>$social_user->getId(), 'provider'=>$provider]
);
return $user;
}else{
$user_id = $authuser->user_id;
$userdata = Constant_model::getDataOneColumn('users',"id",$user_id);
$user = User::firstOrCreate(
['email'=> $userdata[0]->email],
['ip_address'=> '127.0.0.1'],
['user_name'=> $userdata[0]->username],
['name'=> $userdata[0]->name],
['picture'=> $userdata[0]->picture],
['password'=> 'sfdsfsdffsfsfs'],
);
return $user;
}
}}
when i use laravel middleware its routes is not work properly
<?php
namespace App\Http\Controllers;
use Auth;
use App\Article;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
//use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function __construct(){
$this->middleware('auth',['only'=>'create']);
}
//
public function index(){
//return \Auth::user();
$articles = Article::latest('published_at')->published()->get();
return view('articles.index',compact('articles'));
}
public function show($id){
$article = Article::findorFail($id);
//dd($article->published_at->addDays(8)->diffForHumans());
return view('articles.show',compact('article'));
}
public function create(){
if(Auth::guest()){
return redirect('articles');
}
return view('articles.create');
}
public function store(ArticleRequest $request){
/*
$input = Request::all();
$input['published_at'] = Carbon::now();
*/
$article = new Article($request->all());
Auth::user()->articles()->save($article);
//Article::create($request->all());
return redirect('articles');
}
public function edit($id){
$article = Article::findorFail($id);
return view('articles.edit', compact('article'));
}
public function update($id, ArticleRequest $request){
$article = Article::findorFail($id);
$article->update($request->all());
return redirect('articles');
}
}
when i go to http://localhost/lernlaravel/public/articles/create it works fine
but when i go to http://localhost/learnlaravel/public/articles it redirect to http://localhost/articles.
index() method is used for listing articles how i can fix it?
The redirect () accepts a URL path so if you want ensure your redirect will work on both testing and production environments, I would pass either action () or route () to all of your applications redirect calls. In your this case I would go with
return redirect(action ('ArticlesController#show', $articles->id));
This way Laravel will automatically generate the proper URL path to the controller you want to handle the request.
If you choose to go with route() you are required to have named the route in your routes file, but I find that with resourceful controllers it's less complicated to go with action.