1

I'm trying to insert data to Database, but got the error "Creating default object from empty value" and still don't understand, this error come from?

in My Controller

public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required',
            'method' => 'required',
        ]);
        $payrolls = new Payroll();
        $payrolls->employee_id = auth()->user()->id;
        $payrolls->account_id = auth()->user()->id;
        $payrolls->employee_name = $request->get('employee_name');
        $payrolls->description = $request->get('description');
        $payrolls->account = $request->get('account');
        $payrolls->amount = $request->get('amount');
        $payrolls->method = $request->get('method');
        $payrolls->save();
        return response()->json(['created' => true]);
    }

Any help? Thanks......

3
  • 4
    You have typo in your code: $parolls = new Payroll(); It should be $payrolls Commented Dec 17, 2019 at 7:29
  • oh i see, thanks u.. Commented Dec 17, 2019 at 7:32
  • @arm yeah there is typo in his code. z3r0 i have updated your code, you can try with that. Commented Dec 17, 2019 at 7:36

1 Answer 1

0

As @arm stated, you're having a typo in your code, which leads to the error you're getting.
The code below should make it working.
I would also suggest you to use $request->input('****'); instead of dynamic variables like you're doing $request->account;

public function store(Request $request)
{
    $request->validate([
        'amount' => 'required',
        'method' => 'required',
    ]);

    $payrolls = new Payroll();
    $payrolls->employee_id = auth()->user()->id;
    $payrolls->account_id = auth()->user()->id;
    $payrolls->employee_name = $request->input('employee_name');
    $payrolls->description = $request->input('description');
    $payrolls->account = $request->input('account');
    $payrolls->amount = $request->input('amount');
    $payrolls->method = $request->input('method');
    $payrolls->save();

    return response()->json(['created' => true]);
}

You could also have a look at the Payroll::create(), which makes it easier to create a entry in the DB, instead of making a new Payroll(), and saving at the end. https://laravel.com/docs/5.7/eloquent#mass-assignment

Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much for add more detail. but someone told me that my code is bad, can u guide to write a good code.
@z3r0 Well you code will be a lot more readable, and eventually look better, if you're looking into my suggestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.