1
votes

is there a shorter way to insert data in Laravel over the Eloquent ORM?

at the moment i'm doing it this way:

$newCustomerGsale = new CustomersGsale();
$newCustomerGsale->email = $gsalesCustomer->getEmail();
$newCustomerGsale->customerno = $gsalesCustomer->getCustomerNumber();
$newCustomerGsale->created = $gsalesCustomer->getCreated();
$newCustomerGsale->company = $gsalesCustomer->getCompany();
$newCustomerGsale->firstname = $gsalesCustomer->getFirstname();
$newCustomerGsale->lastname = $gsalesCustomer->getLastname();
$newCustomerGsale->save();

like you see all the columns are named like the attributes.

I know u can use the $request object with all() function and fetch(). but I get the data from a other object (soap server).

is there a way to convert this? maybe over the model?

2
use request validators(laravel.com/docs/5.8/validation#validation-quickstart) in laravel. and in controller use all() methodSandeep Sudhakaran
"all the columns are named like the attributes" customerno isn't.brombeer
Delegate the logic to a method in the model like createFromSoapObjectBharat Geleda

2 Answers

0
votes

Your controller

Assume CustomersGsale is your model

public function store(CustomersGsaleFormRequest $request)
{
    CustomersGsale::create($request->all());
}

CustomersGsaleFormRequest.php Laravel Form Requests Validation

public function rules()
{
    return [
        'email'         => 'required|email',
        'customerno'    => 'required',
        'created'       => 'required',
        'company'       => 'required',
        'firstname'     => 'required'
    ];
}

CustomersGsale.php Model

your attributes and columns should be the same. If you are using the create method for store the data then you will need to specify either a fillable or guarded attribute on the model

class CustomersGsale extends Model 
{
    protected $fillable = [
        'email', 'customerno', 'created', 'company', 'firstname', 'lastname'
    ];
}
0
votes
//MyControllerClass
public function store(myCustomValidator $request){
  CustomersGsale::insert($request->all());
}

//myCustomValidator class
public function rules(): array
{
    return [
        'email' => 'required|numeric',
        'customerno' => 'required',
        'created' => 'required',
        'company' => 'required',
        'firstname' => 'required'
        'lastname' => 'nullable'
    ];
}

Try the above method, hope this will work for you.