0
votes

I am trying to save a relationship with the Laravel save method:

public function storeContact(Request $request)
{
    $user = User::firstOrNew(['email' => $request->input('email')]);
    $user->save();

    $message = new App\Message([
        'message' => $request->input('remarks')
    ]);

    $user->message()->save($message);
}
  • var_dump($request->all) confirms both fields are available in the request.
  • All relations work. hasOne, belongsTo are configured in the models. The relation is saved like expected (but message field is empty)
  • When I var_dump($message), there are no attributes in the collection.

I already tried fillable and guarded on the models without any effect. These should not be necessary for the save method though because this uses a full Eloquent model instance.

What am I missing here??

1

1 Answers

0
votes

I think I found the culprit.

When I use a __construct on a model it fails. When I instantiate a model with a __construct no variables are passes as attributes. Even if the __construct is empty.

Test with __construct method

class Message extends Model
    {
        protected $connection = 'system';

        public function __construct()
        {
        }
    // ...
   }

$message = new App\Message(['remarks' => 'Test remarks']);

var_dump(message) // does NOT contain attributes!

Test2 without __construct method

class Message extends Model
    {
        protected $connection = 'system';
    // ...
   }

$message = new App\Message(['remarks' => 'Test remarks']);

var_dump(message) // does contain attributes!

This looks like a bug in Laravel to me.