BusinessService Model
<?php
namespace App\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class BusinessService extends BaseModel implements HasMedia
{
use InteractsWithMedia;
use HasSlug;
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug')
->slugsShouldBeNoLongerThan(50);
}
public function business(){
return $this->hasMany(Business::class);
}
}
BusinessService Controller
public function store(BusinessServiceRequest $request)
{
$service_data=$request->validated();
try {
$service = DB::transaction(function () use ($service_data,$request) {
$service = BusinessService::create($service_data);
if ($request->service_image) {
$service->addMedia($request->service_image)
->toMediaCollection('service_image');
}
return $service;
});
if ($service !== null) {
return responseSuccess(new BusinessServiceResource($service),
201, 'You have saved the service successfully!');
}
} catch (\Exception $e) {
return responseError($e->getMessage(), 500);
}
}
BusinessService Request
<?php
namespace App\Http\Requests\BusinessService;
use Illuminate\Foundation\Http\FormRequest;
class BusinessServiceRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => ['required'],
'description' => ['required'],
'business_id'=>['required'],
'service_image' => ['nullable', 'image']
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
BusinessService Resource
<?php
namespace App\Http\Resources\BusinessService;
use Illuminate\Http\Resources\Json\JsonResource;
class BusinessServiceResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return
[
'id'=>$this->id,
'title'=>$this->title,
'slug'=>$this->slug,
'description'=>$this->description,
'business_id'=>$this->business_id,
'service_image'=>$this->getFirstMediaUrl('service_image'),
'created_at'=>$this->created_at,
];
}
}
API route
Route::apiResource('business-services',BusinessServiceController::class);