skip to Main Content

I am trying to create a model, save it in the database and attach relational data to it. To do this I don’t want to use the database factory, because the database factory uses random values for attributes I didn’t provide.

I tried the following:

$user = User::create([
    'first_name' => $args['first_name'],
    'last_name' => $args['last_name'],
    'email' => $args['email'],
    'password' => IlluminateSupportStr::random(),
]);

$user->client()->associate($client);

dd($user->client);

This returns null for client, but when I do it like this:

$user = User::factory()->create([
    'first_name' => $args['first_name'],
    'last_name' => $args['last_name'],
    'email' => $args['email'],
    'password' => IlluminateSupportStr::random(),
]);

$user->client()->associate($client);

dd($user->client);

It does work. I can see in the Laravel Factory class that it uses the store() method which sets connections in the relations for the model. Could that be reason why the factory generated one does live updates and the manually creates one doesn’t?

Please let me know how I can generate a model like factory without using a factory!

2

Answers


  1. You don’t show your $client on the example. But add save() to the end like the docs.

    $client = Client::find($id);
    
    $user = User::create([
        'first_name' => $args['first_name'],
        'last_name' => $args['last_name'],
        'email' => $args['email'],
        'password' => IlluminateSupportStr::random(),
    ]);
    
    $user->client()->associate($client);
    
    $user->save();
    
    dd($user->client);
    
    Login or Signup to reply.
  2. Briefly, here are some details

    First you have to add save() after associate

    $user->save();
    

    Any model in Laravel has many methods inside it like save create update delete etc …

    DB::table('table_name')->insert([data])
    
    
    ModelName::create([data]);
    
    
    
    $model = new ModelName();
    $model->name = 'value';
    $model->save();
    

    Each of them depends on a different mothod within the model or depends on a different class other than the model, such as the DB

    And each methods of them plays a different role in the background. If you use the Observer Design Pattern, you will find that some of them are Observed and work with the Observer Design Pattern And some of them don’t

    This is the reason for the apparent difference in the event that appeared to you in the result of the dd

    The apparent difference was in dispatches Events

    I hope this helps you to know where the difference comes from to avoid such problems in the future

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search