Laravel storage method

I want to make the eloquent store code more simplistic for something like this:

$keyword = Keyword::create([
        'keyword'       => $request->input('keyword'),
        'micro_price'   => $request->input('micro_price'),
        'macro_price'   => $request->input('macro_price'),
        'cmd'           => $request->input('cmd'),
]);

      

Instead of this:

    $keyword = new Keyword;
    $keyword->keyword = $request->input('keyword');
    $keyword->micro_price = $request->input('micro_price');
    $keyword->macro_price = $request->input('macro_price');
    $keyword->cmd = $request->input('cmd');
    $keyword->user()->associate(Auth::user());
    $keyword->server()->associate($request->input('title'));
    $keyword->save();

      

But there is a problem that I have in the database table keywords with two foreign keys ( server_id

and user_id

), and I want my eloquent model correctly assign these 2 foreign keys, but I do not know how to do it in a simplified version.

Thanks in advance for your help!

+3


source to share


1 answer


Use bulk assignment and all()

query method:

$keyword = Keyword::create($request->all());

      

It will work if you define a property $fillable

in the model Keyword

:

protected $fillable = ['keyword', 'cmd', 'micro_price', 'mini_price'];

      



If you need to associate a keyword with two models, you can manually define foreign keys:

$data = $request->all();
$data['user_id'] = auth()->id();
$data['server_id'] => $request->title;
$keyword = Keyword::create($data);

      

To associate an object with one model, you can use the ratio:

auth()->user()->keywords()->create($request->all());

      

+3


source







All Articles