Lagul
Lagul

Reputation: 199

Create record with Relation Laravel 5.1

Hi i have the next code for create my records

    Institution::create($request->all());



    User::create([
        'name' => $request['name'],
        'lastname' => $request['lastname'],
        'phone' => $request['phone'],
        'email' => $request['email'],
        'password' => $request['password'],
        'state' => 1,
        'profile_id' => 1,
        'institution_id' => Institution::max('id'),
        ]);

The last attributes for the User thats correct implement so? The last 3 user attributes , it is correct to do it that way? or is there a better

Upvotes: 2

Views: 11589

Answers (1)

Ian Gustafson
Ian Gustafson

Reputation: 172

Using Institution::max('id') creates a race condition. Since the create() static method of Eloquent::Model returns the newly-created model, you can just do:

    $institution = Institution::create($request->all());

    User::create([
        'name' => $request['name'],
        'lastname' => $request['lastname'],
        'phone' => $request['phone'],
        'email' => $request['email'],
        'password' => $request['password'],
        'state_id' => 1,
        'profile_id' => 1,
        'institution_id' => $institution->id,
        ]);

Creating a record with known parent ids is generally fine if your goal is to minimize the number of database queries and you have the ids of the related models.

Another way to do it, though it triggers more update queries, is to use Eloquent's built-in methods for adding related models. For example:

    $institution = Institution::create($request->all());

    $state = State::find(1);
    $profile = Profile::find(1);

    $user = new User([
        'name' => $request['name'],
        'lastname' => $request['lastname'],
        'phone' => $request['phone'],
        'email' => $request['email'],
        'password' => $request['password']
        ]);

    $user->state()->associate($state);
    $user->profile()->associate($profile);
    $user->profile()->associate($institution);

    $user->save();

However, in this situation, since the related models are not already loaded, and you know their ids, there is no need to fetch them only to associate them with the User.

Upvotes: 3

Related Questions