Auth::user() not defined in Laravel Route Group - laravel

I'm trying to get auth users data and use it for creating sub-domain.
I found, that I can get need data at single route, such:
Route::get('/', function ()
if (Auth::user()) {
return redirect()->route('home');
}
return view('user.login');
});
But I can't get data in group ruotes. Such I get null:
Route::group(['prefix' => 'dashboard'], function () {
$id = Auth::id();
Route::any($id.'/', 'myController#myAction')->name('some');

Route::get('/', function ()
if (Auth::user()) {
return redirect()->route('home');
}
return view('user.login');
});
It works cause the function is in the same position as a controller in the lifespan of the request. At that sequence, the AuthServiceProviderhas already finished booting.
In the second one, The callback function is part of the routing provider, wich is triggered before assigning the Auth::user().
What you should do, since it's a route for logged in user only, is to have it static
Route::group(['prefix' => 'dashboard'], function () {
$id = Auth::id();
Route::any('/', 'myController#myAction')->name('some');
or
Route::any('profile', 'myController#myAction')->name('some');
And in your controller, you can recover the id
MyConrtoller.php
public function myAction()
{
$id = \Auth::id();
}

Related

How to access data of rate limiters defined in RouteServiceProvider from inside any controller?

In my app/Providers/RouteServiceProvider.php I defined a rate limiter:
protected function configureRateLimiting()
{
RateLimiter::for('auth', function (Request $request) {
return Limit::perMinute(10)->by($request->ip());
});
}
I added this as middleware to my route. Now, in my custom controller I would like to read the remaining attempts. How do I get this info? I tried using RateLimiter::limiter but that returns the callback defined in the for method.
web.php routes:
Route::group(['as' => 'auth.',], function () {
Route::get('login', [AuthController::class, 'index'])->name('login');
Route::post('authenticate', [AuthController::class, 'authenticate'])->name('authenticate')->middleware(['throttle:auth']);
});
Function in my AuthController:
public function authenticate(Request $request)
{
dd( RateLimiter::limiter('auth')->remaining() ); // callback error
dd( RateLimiter::remaining('auth') ); // error because I'd have to hardcode the max attempts here
}

how to send id in route and controller in laravel localization

In my Laravel project with localization I made middleware, route group and all parameters, language switch work correct but when I click to send id by
I get the error:
Missing required parameters for [Route: products] [URI:
{lang}/products/{id}]
My Routes:
Route::group(['prefix' => '{lang}'], function () {
Route::get('/', 'AppController#index')->name('home');
Route::get('/categories', 'AppController#categories')->name('categories');
Route::get('products/{id}', 'AppController#products')->name('products');
Auth::routes();
});
My Middleware:
public function handle($request, Closure $next)
{
\App::setLocale($request->lang);
return $next($request);
}
My AppController:
public function products($id)
{
$products = Category::with('products')->where('id', $id)->get();
return view('products', compact('products'));
}
this is the URL:
http://127.0.0.1:8000/fa/products/1
if I change the above URL manually it works and shows the page:
http://127.0.0.1:8000/1/products/1
But if I click on:
I receive the error.
Since you added a route prefix the first parameter of the products method in your controller will be lang and the second one id.
This should fix the controller:
public function products($lang, $id)
{
$products = Category::with('products')->where('id', $id)->get();
return view('products', compact('products', 'lang'));
}
You need to use a key-value array in route('products', ['lang'=>app()->getLocale(), 'id'=>$category->id]) or whatever your route parameters are named in the original route.
Ref. Laravel Named Routes
PS. as Remul notes, since you have a lang param (as route prefix) the first param in your controller will be $lang then $id
public function products($lang, $id)
{
$products = Category::with('products')->where('id', $id)->get();
return view('products', compact('products'));
}

Laravel Route Always Goes to index

In my Laravel application, I store a new user via Ajax to the DB. The app always calls the index method. What's wrong?
When I remove the Route::post('/users', 'Admin\UserController#store'); route there is a 405 error. That's correct. But why doesn't it go to the store method?
Controller
<?php
class UserController extends Controller
{
public function index()
{
return view('admin.user.index');
}
public function create()
{
//
}
public function store(UserCreateRequest $request)
{
$user = User::createFromRequest($request);
return response()->json(["id" => $user->id]);
}
}
Routes
Route::group(['prefix' => 'admin', 'as' => 'admin.', ], function () {
Route::get('/users/{user}', 'Admin\UserController#show')->name('users.show');
Route::post('/users', 'Admin\UserController#store');
Route::put('/users/{id}', 'Admin\UserController#updateFromDatatable');
Route::delete('/users/{id}', 'Admin\UserController#destroy');
Route::get('/users', 'Admin\UserController#index')->name('users.index');

Laravel 5.2 - Auth::login not preserve when using new \App\User

I've used these code to authenticate username from external source without using database, but laravel 5.2 not save the authentication, and request the external source every time.
class Authenticate
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
$username = getFromExternalSource();
if($username==null){ redirect()->guest('auth/login'); }
$user = new \App\User(['username'=>'admin']);
Auth::login($user);
}
}
return $next($request);
}
}
But when I change Auth::login using $user model get from database it work, I don't know why:
$userDB = \App\User::where('username','=','admin')->first();
Auth::login($userDB);
My route (for example I want to access http://myApp/api)
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => 'auth'], function () {
Route::get('api/', 'ApiController#index');
});
Route::group(['middleware' => ['csrf']], function () {
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
});
});
As far as I know for default authenticate method, you need to pass model that exists in database. In your example you created just object and assigned to it username property.
If you need to authenticate selected user, you should use:
Auth::loginUsingId($id);
(where in place of $id you should pass id of user you want to authenticate - in your case id of user with username admin)

Laravel return Redirect::to not working outside action

I got a weird redirect not working if I put the redirect outside the action. for example :
below code is working
Route::get('/', 'HomeController#index');
public function index()
{
if (Auth::check())
{
$this->user_id = Auth::id();
}
else
{
return Redirect::to('/');
}
// code after check
}
but if I take it out like below, the redirect won't work. It doesn't redirect at all.
Route::get('/', 'HomeController#index');
public function index()
{
$this->authorize();
// code after check
}
private function authorize()
{
if (Auth::check())
{
$this->user_id = Auth::id();
}
else
{
return Redirect::to('/');
}
}
Now if I have to keep using if statement in every action, it will be troublesome. Instead, I will need to call just $this->authorize();
Any idea why it wouldn't work?
You are not returning the result of "return Redirect::to('/');"
Try this:
public function index()
{
return $this->authorize();
}
Just an extra. It seems to be a bad way if I am using the idea of my question. Laravel actually provide routes protection. So, now I change my code with following step :
in app/filter.php change the redirect to which routes you want.
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::guest('/');
});
In your route protect use following code :
Route::get('/', 'HomeController#index');
Route::group(array('before' => 'auth'), function()
{
// The list of routes you want to protect with authentication
Route::get('blabla', 'BlablaController#index');
}
Remove the authorize function on BlablaController
On index function change it as follow :
public function index()
{
$this->user_id = Auth::id();
// code after check
}
Now it will automatically redirect to '/' if its not authenticated
Yes. The auth filter is the best way to implement authentication.
Also, you can make your routes.php easier to read if you use the 'Route:when' to set your filters, like this:
Route::when('path/*', 'auth');
With this, you can minimize writing array('before' => 'auth') on your Route statements.

Resources