Skip to content

Instantly share code, notes, and snippets.

@qadirpervez
Created May 28, 2022 08:35
Show Gist options
  • Save qadirpervez/153a5c00103f92ad618230b20f09cb31 to your computer and use it in GitHub Desktop.
Save qadirpervez/153a5c00103f92ad618230b20f09cb31 to your computer and use it in GitHub Desktop.
Refactoring Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CustomerStoreRequest;
use App\Services\CustomerService;
class CustomerController extends Controller
{
protected $customerService;
public function __construct(CustomerService $customerService)
{
$this->customerService = $customerService;
}
public function store(CustomerStoreRequest $request)
{
$this->customerService->store($request->validated());
return [
'saved' => true,
];
}
}
<?php
namespace App\Services;
use DB;
use Mail;
use App\Mail\WelcomeNewCustomer;
class CustomerService
{
public function store($data)
{
DB::table('customers')->insert($data);
$this->sendWelcomeEmail($data);
}
private function sendWelcomeEmail($data)
{
Mail::to($data->email)->send(new WelcomeNewCustomer($data));
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CustomerStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment