0

Let's say User has a property named 'a_property' , and Post belongs to User. When adding a Post in the create page (which the new Post's user automatically set to the selected User), how can I use the User's a_property as default value of Post's b_value?

YanHao
  • 23
  • 4

3 Answers3

0

Use mutator https://laravel.com/docs/5.7/eloquent-mutators

In Your Post model write function like this, adjust naming

public function setBValueAttribute($value)
{
   $this->attributes['b_value'] = $this->user->a_property;
}
r00t
  • 468
  • 3
  • 10
0

This works for me.

BelongsTo::make('Post')
    ->displayUsing(function ($post) {
  return $post->user->a_property;
}),`
aurawindsurfing
  • 423
  • 4
  • 11
0

You can add a newModel function to your nova resource class:

<?php
use App\Post;

public static function newModel(): Post
{
    $model = parent::newModel();
    $model->a_property = '';

    return $model;
}

Please notice that the newModel() method is called before Nova filled the attributes coming from the request, so we would not get the $post_id. We need to use a event observer to fill the value after the model has been created.

First, create an Observer for Post model

$ php artisan make:observer PostObserver --model=Post

then we can put the codes in the created method

<?php /* file: app/Observers/PostObserver.php */

use App\Post;

public function create(Post $post)
{
    // Assume the relation is `user`:
    $post->a_property = $post->user->a_property;
    $post->save();
}

Also this solution can basically solve the problem, it is not a good idea to store the same value on both User and Post table.