Getting the error "Cannot use object of type Illuminate\Database\MySqlConnection as array" when running queries in transaction block

Viewed 256

Below the code is giving the error in RegisterController when signingup.

protected function create( array $data ) {

        $company = null;
        $user_id = 0;

        DB::transaction( function ( $data ) {
            // Step 1 - Create User
            $user = User::create( [
                'first_name' => $data['first_name'],
                'last_name'  => $data['last_name'],
                'job_title'  => $data['email'],
                'phone'      => $data['email'],
                'email'      => $data['email'],
                'status'     => 0,
                'password'   => Hash::make( $data['password'] ),
            ] );

            // Create the Company
            $user_id = $user->id;

            if ( $user_id > 0 ) {
                $company = Company::create( [
                    'user_id'  => $user_id,
                    'name'     => $data['company_name'],
                    'address'  => $data['address'],
                    'city'     => $data['company_city'],
                    'state'    => $data['state'],
                    'zip_code' => $data['zip_code'],
                    'country'  => $data['country'],
                    'notes'    => $data['notes'],
                    'status'   => 0,
                ] );

                if ( $company->id > 0 ) {
                    return $user;
                }
            }
        } );
    }
1 Answers

The DB::transaction method passes the connection as the first argument to the closure you provide. You want to add $data to the anonymous function's scope. You can read more about it here.

You want:

        DB::transaction(function () use ($data) {
            ....

By passing $data as an argument to the closure, what you are actually getting as $data in the closure is the connection the transaction is being performed on.

Related