Skip to content

Instantly share code, notes, and snippets.

@jekingohel
Last active January 6, 2022 09:42
Show Gist options
  • Save jekingohel/76e2b32f64e50fed50f390cede448833 to your computer and use it in GitHub Desktop.
Save jekingohel/76e2b32f64e50fed50f390cede448833 to your computer and use it in GitHub Desktop.
Write a service class that handles saving and sending email then rewrite the store method
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreCustomerRequest;
use App\Services\CustomerService;
class CustomerController extends Controller
{
public function store(StoreCustomerRequest $request,CustomerService $customerService)
{
$customerService->storeCustomer($request);
return ['saved' => true];
}
}
<?php
namespace App\Services;
use App\Mail\WelcomeNewCustomer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
class CustomerService
{
public function storeCustomer($request)
{
$customer = DB::table('customers')->insert($request->all());
Mail::to($request->input('email'))->send(new WelcomeNewCustomer($customer));
return $customer;
}
}
?>
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreCustomerRequest 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