There is a model User and a model Payments. I need to create a resource such that returns user with successful payment which is identified by a status fields. This is my solutions:
class User extends BaseModel
{
use HasFactory, SearchableTrait, SortableTrait;
protected $fillable = ['name', 'mobile', 'email', 'username', 'hash_id'];
public $searchable = ['name', 'mobile', 'email', 'id', 'user:referred'];
public $sortable = ['name', 'mobile', 'email', 'id'];
protected $table = 'users';
public function invoices()
{
return $this->hasMany(Invoice::class,'user_id');
}
}
and in controller
public function index()
{
$users = new User();
$users = $users::with(['invoices'])->filtered()->sorted();
return UserResource::collection($users->paginate());
}
and
<?php
namespace Modules\User\Transformers;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'mobile' => $this->mobile,
'invoices' => count($this->invoices()->where('status', 2999)->get()),
];
}
}
and model
class Invoice extends Model
{
protected $fillable = [];
protected $table = 'payment_invoices';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function scopeSuccessful($query)
{
return $query->where('status', 2999);
}
}
It seems to be messy solution. I am looking for something to use the scope inside the model relation inside the resource. How can I do that?
$users = new User();You're creating a new user here, does a new user have invoices? (Btw, I'd name it$userinstead of$userssince it only is really one user)