O
O
ObehanProger2019-03-16 19:07:23
Laravel
ObehanProger, 2019-03-16 19:07:23

How to set default field values ​​in eloquent model?

Is it possible to set default values ​​right inside the App\Post model, for example, for the user_id field of the type:
'user_id'=>auth()->user()->id;
so that when creating a record, the current user's id is automatically entered into the table and this would not need to be specified in the create method?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nikolay, 2019-03-16
@ObehanProger

What you want is done through communication.

Auth::user()->posts()->create([
    'title' => 'New Post',
]);

Well, there is still save. Read the docs .
It is very short-sighted to hard-code the binding to authorization in the attributes, don't do it.
Well, or if you really want to, then use the boot function, and then either through the observer, or through the redefinition of creating

V
vism, 2019-03-16
@vism

$attributes = [
'''
]

A
Alex Wells, 2019-03-16
@Alex_Wells

It is possible, but not necessary, especially if you do not know how.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question