Laravel update Session manually - laravel

I am using Laravel 5.4 and I am using builtin Auth so Logging in - out comping behind the scene and it's storing the session automatically.
How can I add more information to my session ?

If you don't want to build a custom Login function, you could go to
AuthenticatesUsers file which handle this task and inside method called
authenticated(Request $request, $user)
You can add whatever you want.
This file can be found in
vendor->Laravel->framework->src->Illuminate->Foundation->Auth

Nour answer works but it's better if dont write code directly in vendor files, it can be overwritten by any composer update.
Instead you can add a function authenticated(Request $request, $user) directly in your App\Http\Controllers\Auth\LoginController and write your custom code that fires on every successful authentication.

Whatever you store in your user table will be stored in session data after log in you just need to access it like this
Auth::user()->column_name

Related

Where to check if an User is logged in in a Laravel Application?

I've been using your advice and View::sharing all of my important data to all views. However, there is one issue I have encountered.
This code:
if(!Auth::guest()){
$user=Auth::user()->id;
}
else $user=0;
$temp=DB::select('query');
View::share('cartnumber', count($temp));
View::share('cartitems', $temp);
doesn't work when put in AppServiceProvider. Or better, it always sets $user=0, even if I am logged in. I thought it is because AppServiceProvider's boot function executes before the site checks if someone is logged in.
I then tried to use a BaseController with a construct function but that doesn't work either. The only solution that seems to work correctly is putting the code in every single Controller for every view! That actually works, which kind of confirms my theory.
But is there anywhere I can put this code without having to copy/paste it in every single Controller? Thanks in advance!
You'd likely want to put this code later in the request life cycle to guarantee an auth user because as others have mentioned middleware/session code has not occured during this part of the framework booting up. You could use a service class to call in all your controllers to avoid the copy pasting. Or If you'd like to achieve this using code in your service provider you could use a View Composer instead of a share this allows you to define a callback/or class that will be called right before the view is returned
view()->composer(['/uri-that-needs-data'], function ($view) {
if (Auth::check()) {
$cart = DB::query(...)->get();
$view->with('cartitems', $cart);
}
});
Check out https://laravel.com/docs/5.7/views#view-composers for more details.
Auth::user() will be empty until the session middleware has run.
The reason you can't access the user inside your service provider is because that code is run during the "bootstrapping" phase of the application lifecycle, when it's doing things like loading filesystem or cache drivers, long before the request is sent through response handlers (including middleware).
Once the application has been bootstrapped and all service providers
have been registered, the Request will be handed off to the router
for dispatching. The router will dispatch the request to a route or
controller, as well as run any route specific middleware.
Source: https://laravel.com/docs/5.7/lifecycle
If you don't want to copy/paste that code everywhere, then one place to put it is in custom route middleware. You can list it after the auth middleware to guarantee a logged-in user.
Edit: View composers are another really good option, as suggested by #surgiie. The reason these can be set up inside a service provider (unlike your example) is because the view composer registers a callback, but doesn't execute it until a much later stage in the application lifecycle.

Laravel - deleting a guest user after the user logs out

I am using Laravel 5.4 and I want to delete a guest user from the users table after he logs out. So I created a LogoutEventListener class (followed instructions from documentation) and I am able to successfully delete the user in the handle(Logout $event) function.
However I am unable to determine if Laravel's own logout() function in AuthenticatesUsers trait is called either before or after the above handle function. Add(...) statement at the beginning of this function never seems to be called. So I am afraid of any unforeseen sideeffects.
So, is it safe to delete the user in the LogoutEventListener::handle() function?
Those are events for laravel 5.2 +
$events->listen(
'Illuminate\Auth\Events\Logout',
'App\Listeners\UserEventSubscriber#onUserLogout'
);

laravel modify how the password is checked in the authentication process

I am using laravel 5.2.
I would like to be able to change a parameter in the .env file like PASSWORD_VALIDATION=...
This could be either LARAVEL or PERSONAL.
If it is LARAVEL then it would use the standard Laravel authentication method with users and passwords in the db. But if I use PERSONAL, I would like that it uses a function I have created that will check if the email address is in the database then verify the password provided with the Active Directory in my company.
I looked at the various files and I can see I have:
app\Http\Controllers\Auth\AuthController.php
In there, I can see:
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
In this file:
vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.php
It uses
use AuthenticatesUsers, RegistersUsers {
AuthenticatesUsers::redirectPath insteadof RegistersUsers;
AuthenticatesUsers::getGuard insteadof RegistersUsers;
So I can see in the file
vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php
My function to be changed which is:
public function postLogin(Request $request)
{
return $this->login($request);
}
I have tried to copy this one in my file app\Http\Controllers\Auth\AuthController.php but it doesn't change anything if I modify what is inside it...
Thanks
Ok, I found out why, it seems that in my routes, it is pointing to #login and not to #postLogin hence any modification applied to the function postLogin wouldn't do anything

How to globally prevent saving to database in Laravel 5

I made a PHP script in Laravel and now I want to show demo to my buyers. Since I don't want them to make any changes to the database, I was wondering if there is a way to globally disable any saving to the database?
If you have a BaseModel that extends Laravel's default Eloquent model class. And all of your applications models extend that BaseModel you can add the following to it:
public static function boot()
{
parent::boot();
static::saving(function($model)
{
return false;
});
}
This will intercept any creating or updating events from Eloquent.
This may be the technical answer for your question, but ideally just backup your db and restore it after showing to your buyers.
The easiest thing will be to create a mysql user that hasn't permissions to insert. Use the following mysql statement to create the user and use this user as the user in your database setting. I don't think there's a global method for this in laravel.
GRANT SELECT ON [database name].[table name] TO ‘[username]’#'%’;
This way, your user can view everything, but isn't able to save a bit.

Laravel 5 - Is there a way to use built-in authentication but disable registration?

I am building an administrative back-end and thus need to hide public user registration. It appears that if you want to use the built-in Illuminate authentication you need to add
use AuthenticatesAndRegistersUsers to your controller definition. This trait is defined here.
It appears as if it is impossible to disable registration if you want to use the built-in auth handlers... can someone show me wrong?
I'm using Laravel 5.2+ and I found that if you remove the Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers and use just Illuminate\Foundation\Auth\AuthenticatesUsers does the trick too.
Though /register is still accessible and will throw a fatal error.
This page talks about overriding the auth controller. Its worth a read, at a basic level it seems you can add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function getRegister() {
return redirect('/');
}
public function postRegister() {
return redirect('/');
}
So if a user accesses the registration url it will redirect them away to a place of your choosing.
You can have your own form of registration. The only thing Laravel does is make it easy to authenticate on a users table because they create the model, build the db schema for users and provide helper methods to authenticate on that model/table.
You don't have to have a view hitting the registration page... But if you want to use the built in auth you still need to use (or set) a Model and a driver for database connections.
You can just remove that view and/or controller method from the route that links to the registration view and create your own (or seed the database manually).
But, no, you cannot forgo using Eloquent, and the User model and expect to use built in auth. Built in authentication requires that you specify settings in /config/auth.php. You may specific a different model (other than User) and you may specify a different table, but you cannot forgo the configuration completely.
Laravel is very customizable though, so you can achieve what you are looking to do... plus why not use Eloquent, it's nice.
Based on #shoo's answer, working with Laravel 5.2
Add the following lines to app\Http\Controllers\Auth\AuthController.php :
public function showRegistrationForm() {
return redirect('/');
}
public function register() {
return redirect('/');
}

Resources