Create a bright object with the included ratio

I have a lot of new things for opps and laravel as So, to insert values ​​into a table usersand profileswhich has a relation hav OneToOne, Here is what my method looks likestore()

public function store(Requests\StoreNewUser $request)
{
    // crate an objct of user model
        $user = new \App\User;
        // now request and assign validated input to array of column names in user table
        $user->first_name = $request->input('first_name');
        $user->last_name = $request->input('last_name');
        $user->email = $request->input('email');
        $user->password = $request->input('password');
        /* want to assign request input to profile table columns in one go 
        */
        $user->profile()->user_id = $user->id; // foreign key in profiles table
        $user->profile()->mobile_no = $request->input('mobile'); 
        dd($user); // nothing related to profile is returned
}

I am creating a new record, so it dd()never returns anything related to the profile table.

Is this because the object $userdoes not include the default relationship? If so, can I create an object $userthat includes related relationships in UserModel?

Or I need to create two separate objects for each table and save()data.
But what is the meaning of the method push()?

EDIT 1 Postscript yes, relationships are already defined in Userand Profilemodel

+8
4

- . :

$user = new \App\User;
$user->first_name = $request->input('first_name');
// ...

$user->save();

, - :

$profile = new \App\Profile(['mobile_no' => $request->input('mobile')]);
$user->profile()->save($profile);

, profile User:

public function profile()
{
    return $this->hasOne('App\Profile');
}
+10

, Laravel 5 . @The Alpha answer .

$profile = new \App\Profile(['mobile_no' => $request->input('mobile')]);
$user->profile()->associate($profile); // You can no longer call 'save' here
$user->profile()->save();

, save belongsTo ( ), Illuminate\Database\Query\Builder.

+3

, $user ? $user, User Model?

, , .

User - :

public function profile()
{
    return $this->hasOne('App\Profile'); // or whatever your namespace is
}

Profile.

: http://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

Alpha, , , , .

0

User Class:

public function profile()
{
    return $this->hasOne(App\Profile::class);
}

:

public function store(Requests\StoreNewUser $request)
{
    $user = App\User::create(
        $request->only(
            [
                'first_name',
                'last_name',
                'email'
            ]
        )
    );

    $user->password = Illuminate\Support\Facades\Hash::make($request->password);
    //or $user->password = bcrypt($request->password);

    $user->profile()->create(
        [
            'mobile_no' =>  $request->mobile;
        ]
    );

    dd($user);
}

, , , , ,

0

All Articles