0

It keeps giving failed via my controller when trying to make the post request. I'm trying to make a file upload and storing that file name associated with the user into my db. I'm not sure what I'm doing wrong here, I've tried many ways to fix this but to no avail as I've hit a wall. I believe it may be the way my code's written in my controller but I'm not too sure.

The error I'm getting in the logs is Call to a member function photos() on null which means auth()->user() is not detecting the authenticated user and there lies the problem which begs the question - how? I'm logged in using correct credentials without issues. How come I can't validate in a separate controller?

What am I doing wrong and how can I fix this?

Note: My React.js and Laravel code bases are separated.

Here's my react form submission:

handleSubmit(e) {
    e.preventDefault();
    console.log("here in submitHandler()");

    let access_token = Cookies.get("access_token").slice(13, -8);

    const headers = {
        Authorization: `Bearer ${access_token}`
    }

    console.log(this.state.file_path);

    axios.post('http://myendpoint/api/auth/dashboard', this.state.file_path, {headers})
        .then(response => {
            console.log(response);
        }).catch(error => {
        console.log(error);
    })

};

Here's my FileUploadController.php:

public function uploadTest(Request $request) {
    if(auth()->user()) {
        auth()->user()->photos()->create([
            'file_path' => $request->file('fileToUpload')->getClientOriginalExtension()
        ]);
        return response()->json($request->session()->get("user"));
    }
    return "failed";
}

Here's my User model:

public function photos() {
    return $this->hasMany(Photo::class);
}

Here's my Photo model:

public function user() {
    return $this->belongsTo(User::class);
}

Here's my auth for creating user and logging in (AuthController.php):

public function signup(Request $request) {
    $request->validate([
        'name' => 'required|string',
        'email' => 'required|string|email|unique:users',
        'password' => 'required|string|confirmed'
    ]);
    $user = new User([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password)
    ]);
    $user->save();
    return response()->json([
        'message' => 'Successfully created user!'
    ], 201);
}

public function login(Request $request) {
        $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string',
            'remember_me' => 'boolean'
        ]);
        $credentials = request(['email', 'password']);
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('Personal Access Token');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        $request->session()->put("user", $user);
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString(),
            $user
        ]);
    }
cloudyday
  • 183
  • 6
  • Can you print and share value of `auth()->user()` ? – Ali Akbar Azizi Jun 06 '20 at 00:55
  • @AliAkbarAzizi if I run `dd(auth()->user());` outside of the `if()` condition, then I get an error in console that says: `Access to XMLHttpRequest at 'http://my/api/endpoint' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.` – cloudyday Jun 06 '20 at 01:23
  • You try to make CORS request, you should make request with same domain, of if you want to use it only for test use extesnion like CORS Everywhere for firefox or allow it in php code https://stackoverflow.com/a/7564919/1827594 – Ali Akbar Azizi Jun 06 '20 at 17:19

0 Answers0