What is `closure` middleware in laravel? - laravel

When I route:list all routes in the system, I find some of the routes have Closure middleware.
Although I did only assign api and auth a middlewares
api.php
Route::post('api/favorites/{post}', 'api/favorites/{post}')->middleware('auth');
Output
| Method | URI | Action | Middleware
-------------------------------------------------------------------------------------
| POST | api/favorites/{post} | \FavoritesController#favorite | api,auth,Closure

Middlewares can be set as a Closure as well. In case you need a middleware for a single usage only then you don't need to create a dedicated middleware for that. Instead, you can just add a Closure middleware in your Controller's __construct:
public function __construct(Request $request)
{
$this->middleware(function ($request, $next) {
//your logic
return $next($request);
});
}

Related

Auth::check fails in middleware

Can somebody explain why this strange behavior of Laravel is happening? Basically, I am trying to create a middleware for my application
public function handle(Request $request, Closure $next)
{
if (auth()->check()) {
$expires = Carbon::now()->addMinute(2);
\Illuminate\Support\Facades\Cache::put('user-is-online-' . Auth::user()->id, true, $expires);
}
return $next($request);
}
}
But auth()->check it is keep failing and not returning true , (user is authenticated) , auth()->check is working in other places like web routes and controllers method but why not here ?
If you are using auth middleware to protect your routes, then make sure this auth middleware is set to run before your middleware, otherwise auth()->check() will return false. Try php artisan route:list and check the orders of middlewares for your specified route.

Route in laravel

I am a newbie to Laravel. I am getting this error. Please advise?
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/Dashboard',function(){
return view('layouts.master');
})
Just add a ; at the end of line 22.
Route::get('/Dashboard',function(){
return view('layouts.master');
}) // <---- HERE
Like this:
Route::get('/Dashboard',function(){
return view('layouts.master');
});

Non-static method Illuminate\Routing\Route::middleware() should not be called statically

I have encountered this error in this file : route/api.php
This error refers to line 16
<?php
use Illuminate\Http\Request;
use Illuminate\Routing\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!
|
*/
16- Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request::user();
});
Route::post('login', 'Api\AuthController#login');
Problem solved by changing this line
from
use Illuminate\Routing\Route;
to
use Illuminate\Support\Facades\Route;
Since You've not defined in Your question what is error message I can only predict that You're using middleware incorrectly.
Middleware should be assigned to group.
Route::middleware('auth:api')->group(function() {
Router::get('/user', function (Request $request) {
return $request::user();
});
});
or You've to use middleware after defining the route handler:
Route::get('/user', function(Request $request) {
return $request::user();
})->middleware('auth:api');
Because the method middleware is not static method, according to the assigning-middleware-to-routes try it like this:
Route::get('/user', function (Request $request) {
return $request::user();
})->middleware('auth:api');

Laravel 5 Auth::user() is empty everywhere except index() function and blade template

I've been trying for some time to figure this out, but no solution I found was conclusive. Basically I'm trying to retrieve a list of clients based on the user logged in, but I cannot retrieve the user object anywhere in the controller except the index() function where is returns the view, and also the blade template that displays the logged in user's name.
This is my ClientController.php:
<?php
namespace App\Http\Controllers;
use App\Http\Models\Client;
use App\Http\Requests\GetClientsRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
class ClientController extends Controller
{
protected $user;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
/**
* Show the clients page.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
Log::info("client user: " . print_r($this->user, 1));
return view('page');
}
public function getClients()
{
$currentUser = Auth::user();
if ($currentUser) {
$clients = Client::with('account')
->where('user_id', $currentUser->account)
->get();
$collection = collect($clients);
return response($collection->toArray());
}
}
}
The Log in the index function prints out the user object no problem - but when it's called in the getClients() function, it's empty. I also tried using this in the __construct():
$this->middleware('auth');
As per the Laravel template I was using, but whenever I call the getClients API route I always get a 401 Unauthorized error.
Here is my api.php routes file (although only currently using the getClients call) :
<?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::get('welcome-message', 'DashboardController#getWelcomeMessage');
Route::prefix('clients')->group(function () {
Route::get('/', 'ClientController#getClients');
Route::get('/{clientId}', 'ClientController#getClient');
Route::post('/', 'ClientController#postCreateClient');
Route::put('/{clientId}', 'ClientController#putUpdateClient');
});
And my web.php routes file:
<?php
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Auth::routes();
Route::get('/', 'HomeController#index')->name('dashboard');
Route::get('/clients', 'ClientController#index')->name('clients');
The system knows I'm logged in, because I wouldn't even be able to visit the client dashboard at all, so I don't understand why I cannot get a result from Auth::user() in the function - unless I'm using the middleware incorrectly?
You will have to use the auth:api middleware to allow API authentication.
To do so, add this middleware to your API route, omit in that case to add middleware in the __constructor.
Route::group([
'prefix' => 'clients',
'middleware' => ['auth:api']
], function(){
Route::get('/', 'ClientController#getClients');
// ... etc
});
Make sure that you have a valid access token to access your API. When using your API with a JS front-end, read about it in the Laravel docs.
Note that 'web' authentication (middleware: auth) uses a different mechanism than API authentication (middleware: auth:api) to authenticate users.

Laravel 5.2 Authentication - How can I show logged in user's name and the logout link in every page?

Laravel 5.2 Authentication
I created a new authentication scaffolding in Laravel 5.2 using
php artisan make:auth
everything worked perfectly except I get Login/Register links even after logging in when I'm in route
/
but it shows the user's name with a logout link (which is what I want to have in every page) when I'm in route
/home
How can I show logged in user's name and the logout link in every page?
This is because, you are not using the auth middleware on you / route. In your routes.php file the default for this is:
Route::get('/', function () {
return view('welcome');
});
Try moving this closure into the web middleware that was added in when you generated the scaffolding. Your routes.php file should look something like this when complete:
<?php
/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
// Route::get('/', function () {
// return view('welcome');
// });
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/
Route::group(['middleware' => ['web']], function () {
//
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
// Add this!
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
});

Resources