Home > OS >  How to fill DTO object Spatie in Laravel?
How to fill DTO object Spatie in Laravel?

Time:11-07

I use DTO from Spatie in Laravel.

The DTO model looks like:

<?php

namespace Domain\Subscriber\DataTransferObjects;

use Spatie\LaravelData\Data;


class Rating {
    public int $rateid;
    public int $rate;

}

class RateData extends Data
{

    public Rating $rating = array();

    public function __construct() {

    }
}

I fetch the request inside controller:

{"rating": [{"rateid": 1, "rate": 4}]}

How to fill the DTO by this request?

Controller is:

class RateController extends Controller
{


    public function index(Request $request)
    {
        $RateData = new RateData()
        $service->setRate();
    }

CodePudding user response:

I see no point in wrapping Rating in RateData, as it is just simple data.

class Rating extends Data
{
    public int $rateid;
    public int $rate;
}

In your controller.

$rating = Rating::from(
    [
        'rateid' => $request->get('rating.rateid'),
        'rate' => $request->get('rating.rate'),
    ]
);

Just a general tip, keep consistent with naming, that is gonna help you in the long run.

Pascal case is used for $RateData and the DTO, uses all lowercase on $rateid;. PHP property for an example should be camel cased. $rateId or $rateData.

  • Related