Edu Ruiz
Edu Ruiz

Reputation: 1877

Can't get user_id Laravel with Auth::user() just with \Auth::user()

sorry if it is a noob question, but I'm trying to learn laravel on laracast and can't solve this by my own.

there is a store function on my ArticlesController like this:

public function store(ArticleRequest $request)
    {
        $article = new Article($request->all());

        Auth::user()->articles()->save($article);

        return redirect('articles');
    }

and it returns a blank page, making clear that is some error, but if I change to

    \Auth::user()->articles()->save($article);

it works as expected, saving the article with the user_id field.
I tried import with use App\Http\Controllers\Auth\AuthController; but I think this is not the way.

*obs: Laravel 5.0

Upvotes: 2

Views: 1183

Answers (1)

Alana Storm
Alana Storm

Reputation: 166066

In modern PHP, if you see the following at the top of a file

namespace App\Foo\Bar;

it means all the code inside that file in part of the App\Foo\Bar namespace. If you try to use a namespaceless class inside this file

$object = new Auth;

PHP will assume you want to use the class. In other words, it's the same as saying

$object = \App\Foo\Bar\Auth;

When you say

\Auth

you're telling PHP "use the global, top level namespace class named Auth.

This is a perfectly valid use of PHP, by the way. However, if you don't like using the global \ -- you can import the \Auth class into your PHP file (sometimes referred to as a "module" in other languages") by using the use statement.

namespace App\Foo\Bar;

//pull in the global class `Auth`
use Auth;
//...

$foo = new Auth;

Upvotes: 7

Related Questions