Jerico Pulvera
Jerico Pulvera

Reputation: 1042

How to use Auth class from Laravel Framework in normal PHP file

I have an integration.php file which is in public/arrowchat/includes/integration.php

I was wondering how do I access the Auth class within there.

I have tried this but it doesn't seem to work.

<?php
    use Auth;

    function get_user_id() 
    {
        if (Auth::guest()) 
        {
            return NULL;
        } else {
            return Auth::user()->id;
        }
    }
?>

Upvotes: 2

Views: 282

Answers (1)

Denis Mysenko
Denis Mysenko

Reputation: 6534

If you want to use Auth facade in a plain (read - invoked/executed directly, not within the the framework) PHP file, you still need to require composer autoloader so that classes such as Auth are loaded. In your example above, you are most likely to get an unknown class error.

But even then, Auth most probably relies on classes like Request to get the headers and cookies and Request is initialised in Laravel bootstrap.

If you really, really need to do this - you will have to copy/paste some of the bootstrap stuff from Laravel's bootstrapper in order to make this work.

Otherwise, I would recommend you to make a Laravel console command instead and then everything will just work out of the box.

Upvotes: 1

Related Questions