Jerielle
Jerielle

Reputation: 7520

Unable to access related model using Laravel

I am trying to add User profile and my problem is I can't access my related model.

What I want is to add another information for the user. In using tinker I can add the profile. Here's what I did in tinker:

$user = new App\User;
$user->username = 'sampleusername';
$user->name = 'Bruce Lee';
$user->email = '[email protected]';
$user->password = bcrypt('password');
$user->save();

$profile = new App\UserProfile;
$profile->phone = '123456789';
$profile->address = 'unknown';
$user->profile()->save($profile);

By this approach I am able to add additional information but when I modified the RegisterController

I got this error:

Class 'App\Http\Controllers\Auth\App\UserProfile' not found

Here's what I modified:

 protected function create(array $data)
    {
        $user = User::create([
            'name'      =>  title_case($data['lastname']) . ' ' . title_case($data['firstname']),
            'username'  =>  $data['username'],
            'email'     =>  $data['email'],
            'password'  =>  bcrypt($data['password']),
        ]);

        if($user) {

            $profile = new App\UserProfile;
            $profile->phone = $data['phone'];
            $profile->address = $data['address'];

            $user->profile()->save($profile);

            return $user;

        }

    }

Can you help me with this?

Upvotes: 1

Views: 70

Answers (3)

Alexey Mezenin
Alexey Mezenin

Reputation: 163968

You should use full namespace. You can add use clause to the top of the controller:

use App\User;

Or you can use full namespace:

App\User::create();

Update

In the comments, you've asked about creating a user. Do this:

$user = User::create([
        'name'      =>  title_case($data['lastname']) . ' ' . title_case($data['firstname']),
        'username'  =>  $data['username'],
        'email'     =>  $data['email'],
        'password'  =>  bcrypt($data['password']),
    ]);

$user->profile()->create(['phone' => $data['phone'], 'address' => $data['address']]);

return $user;

Upvotes: 2

zgabievi
zgabievi

Reputation: 1212

Update your code like this:

$profile = new \App\UserProfile;
$profile->phone = $data['phone'];
$profile->address = $data['address'];

$user->profile()->save($profile);

return $user;

Or after namespace in your php controller file, add this: use App\User; and use App\UserProfile. Then you will be able to use User and UserProfile without App namespace in your code.

Upvotes: 0

ka_lin
ka_lin

Reputation: 9442

Looks like you forgot to add :use App\User; right after the current controller's namespace.

In the end you should have something like:

namespace App\Http\Controllers\Auth\App; use App\User; <- this class UserProfile{...}

By default php tries to resolve the class in the current namespace

Upvotes: 1

Related Questions