assign middleware to controller laravel - php

I have laravel 5.6 project
and I have registered middleware called permissions. I need to assign this middleware in a controller, but not for the whole controller- just for one function without using __construct().
I mean I want to assign this in:
public function index()
{
$this->middleware('permission');
}
I've tried it like this, but its not working. It's worked when I use it inside:
public function __construct()
{
$this->middleware('permission');
}
But I don't need it like that.
Thanks.

Middleware can only be registered in the constructor. You can use the only() method though, like:
function __construct()
{
$this->middleware('permission')->only('index');
}
I believe you can pass an array of middlewares as well. There's also the except() method that does the opposite.

Here is your solution:
public function __construct()
{
$this->middleware('permission')->only('index');
}

Related

Laravel adding middleware inside a controller function

as the title says I want to use a middleware inside a controller function. I have resource controllers, which their functions inside will have different access rights so I can't use a middleware in the web.php file, I have to use or apply it separately in each function to limit access, my googling hasn't been successful in getting a solution to that so far. Any help please and thanks in advance.
P.S. I believe no code is necessary here.
Middleware could also be applied to just one function, just add the method name in your controller constructor
public function __construct()
{
// Middleware only applied to these methods
$this->middleware('loggedIn', [
'only' => [
'update' // Could add bunch of more methods too
]
]);
}
OR
public function __construct()
{
// Middleware only applied to these methods
$this->middleware('loggedIn')->only([
'update' // Could add bunch of more methods too
]);
}
Here's the documentation
There are 3 ways to use a middleware inside a controller:
1) Protect all functions:
public function __construct()
{
$this->middleware('auth');
}
2) Protect only some functions:
public function __construct()
{
$this->middleware('auth')->only(['functionName1', 'functionName2']);
}
3) Protect all functions except some:
public function __construct()
{
$this->middleware('auth')->except(['functionName1', 'functionName2']);
}
Here you can find all the documentation about this topic: Controllers
I hope this can be helpful, regards!
Use the following code inside your controller constructor. The following code will use the auth middleware:
public function __construct() {
$this->middleware('auth');
}
Also you can simply add middleware at your routes. For example I need to add middleware for my method "registration_fee()" inside "RegisterController", so it will looks like this:
Route::get('/pay_register_fee', 'Auth\RegisterController#registration_fee')
->name('pay_register_fee')->middleware(['guest', Register::class, RegistrationFee::class]);
"RegistrationFee" is middleware that I want to add.
P.S. Not forget import class or write full path to middleware.

How to change default Laravel Auth login view

I'm trying to change the default login view, from Laravel Auth. Earlier suggestions points at modifying the path inside of the corresponding controller, under /vendor. However, this is a cooperative project, so modifying the vendor files is not an option.
By default the view for Auth login is auth.login, but i want it to be backend.pages.login.
In which other way can i accomplish this?
I have also tried to manually add the view routes in the router, but it won't recognize Auth as a class, no matter how i wire it up.
Note: It's Laravel 5.3
Thanks in advance
In App\Http\Controllers\Auth\LoginController define a fuction named showLoginForm() as:
public function showLoginForm()
{
return view('custom.login');
}
It overrides the function showLoginForm defined in the trait Illuminate\Foundation\Auth\AuthenticatesUsers.
Note: In Laravel 5.3 the function name is changed from getLogin to showLoginForm.
Since the question was already answered I'll give the same example for the current version of Laravel.
If you're on Laravel 5.6 and up, this functionality should be put in
app/Http/Controllers/Auth/LoginController.php
public function showLoginForm()
{
return view('custom.login');
}
Also, if you would like to add a parameter to this, you can do so if you specify it in your web route like this:
Route::get('login/{page?}', 'Auth\LoginController#showLoginForm')->name('login');
Then you can do something like this:
public function showLoginForm($page = null)
{
if(isset($page)){
// do something
// example: return view('auth.login', compact('page'));
}
return view('auth.login');
}
Tip: if you don't have the LoginController in your project make sure you run
php artisan make:auth
in your AuthenticatesUsers trait override this method :
public function showLoginForm()
{
return view('login');
}
trait AuthenticatesUsers
{
use RedirectsUsers, ThrottlesLogins;
/**
* Show the application's login form.
*
* #return \Illuminate\View\View
*/
public function showLoginForm()
{
return view('front.login'); //you can change every path you want
}

Laravel global variable for base layout

I have a few things that I want to present on every page, like $gameAccounts = Auth::user()->gameAccounts()->get();
What would be the best approach to present this variable globally, on each page?
If you need it only for the views you can use a view composer in your AppServiceProvider
public function boot()
{
View::composer('layouts.base', function ($view) {
$view->with('gameAccounts', Auth::user()->gameAccounts);
});
}
If you need it globally you can store it in a config also in AppServiceProvider.
For shared functionality I would recommend to write a trait. The trait can be used throughout your controllers and provide the same functionality for all.
Example:
trait GameSettingsTrait
{
public function getUserGameAccounts()
{
return Auth::user()->gameAccounts()->get();
}
}
In your controller do:
class IndexController extends Controller
{
use GameSettingsTrait;
...
Another approach would be to put the logic in the base controller in app/Http/Controllers/Controller.php. Btw, there you can see that it already uses traits for other functionality.
You need to use view composer.
Look at the doc.
https://laravel.com/docs/5.2/views#view-composers
Use view composer is a best way to do this.
Just add this rows to your AppServiceProvider.php inside boot method:
public function boot()
{
//
view()->composer('*', function ($view) {
$view->with('user', Auth::user()->gameAccounts()->get());
});
}

Laravel 5: Global Auth $user variable in all controllers

In my BaseController I have this:
public function __construct()
{
$user = Auth::user();
View::share('user', $user);
}
I can access the $user array throughout all of my views but what if I want it to be a global variable available in all of my Controllers?
I have the following working code:
use Auth;
use DB;
class UsersController extends BaseController
{
public function index()
{
$user = Auth::user();
$users = DB::table('users')->where('user_id', $user->user_id)->get();
return view('pages.users.index', compact('users');
}
}
I want the $user variable available in all of my controllers and within all of the public functions within each on the controllers but I don't want to have to redeclare "use Auth;" and "$user = Auth::user();"
I tried adding it to a __construct in the BaseController but that didn't seem to work, Undefined $user variable error. Any thoughts? I know it's possible.
Has shown in other answers, you can:
set it as a property of your base controller (I don't recommend this, it just adds clutter)
create a custom helper (see below)
just do \Auth::user()
Another technique, you can use auth() helper:
auth()->user()
It is even documented.
According to this PR, there is no plan to add an user() helper in Laravel.
If you consider it is worth adding this helper to your project, here is the code:
function user()
{
// short and sweet
return auth()->user();
// alternative, saves one function call!!
return app('Illuminate\Contracts\Auth\Guard')->user();
}
I do not see why something like this would not work:
public function __construct()
{
$this->user = \Auth::user();
\View::share('user', $this->user);
}
This way it's available to all your views and as long as your controllers are extending BaseController, it's available in all your controllers as well with $this->user.
Why don't you use a helper function. It won't give you a $user variable, but it can give you a more cleaner way to accomplish this.
In your helpers.php add a function:
function getUser(){
return Auth::user();
}
In all other places (controller, views, models) call: getUser(). That's it.
If you don't have any helper file for your functions yet. You can follow this link to create one.
I don't see whats the issue with using Auth::user(), this class is using singleton pattern which means that if the Auth::user() is already initialized it won't check again against the database especially when most of the code shouldn't even be inside a controller so basically you would still need to do Auth::user() inside your services, models, form requests, etc..
abstract class Controller extends BaseController {
protected $user;
use ValidatesRequests;
public function ___construct(){
$this->user = \Auth::user();
}
}

Create constructor method in controller in Yii

I have just started to learn Yii, where I have created one PostController Controller. In this controller I am having one requirement of using Sessions.
So I have created one constructor method and its code is as follows
public $session;
public function __construct() {
$this->session = new CHttpSession;
$this->session->open();
}
But after creating this constructor the controller was not working and gives error. And after deleting this code my controller was working perfectly. I have written this code inside constructor to not initialize the Session in each method for actionCreate and actionUpdate.
So my question is how can we create constructor in Yii?
Thanks
You simply forgot to call parent constructor :
public function __construct()
{
.....
parent::__construct();
}
You could use beforeAction instead of overriding __construct.
And Sergey is right, by default Yii will start session (autoStart), you just have to use Yii::app()->session, e.g. :
Yii::app()->session['var'] = 'value';
public function __construct()
{
parent::__construct($this->id, $this->module);
}
I use init() for that, but found what people think __construct is better.

Categories