jeudi 25 juillet 2019

How to return null with Illuminate\Http\Resources\Json\JsonResource?

I want to return null if model has some invalid conditions, but it is always return [].For example,

$productTemplate['gift'] = new GiftTemplate($gift);

use Illuminate\Http\Resources\Json\JsonResource;

class GiftTemplate extends JsonResource
{
    public function toArray($request)
    {
        if ($this->expired_at < now() || $this->is_disabled || $request->user()->age > 20)  {
            // I want to return null here for $productTemplate['gift'],
            // but it is always return [] when resource is null in JsonResource@toArray. 
            // The [] is not friendly for frontend.
            return null; 
        }

        $this->setVisible([
            'id',
            'name',
        ]);

       $data = parent::toArray($request);
        return $data;
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire