Skip to content

Instantly share code, notes, and snippets.

@paradisetester
Created January 3, 2022 08:01
Show Gist options
  • Save paradisetester/d63239c1230acee63a167e4eae85a209 to your computer and use it in GitHub Desktop.
Save paradisetester/d63239c1230acee63a167e4eae85a209 to your computer and use it in GitHub Desktop.
service class that handles saving and sending email then rewrite the store method
<?php
namespace App\Http\Controllers;
use App\Providers\CustomerServiceProvider;
use Illuminate\Http\Request;
use App\Models\Customer;
use Validator;
class CustomerController extends Controller
{
public function index()
{
return view ('customer.index');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
'email' => 'required|email|unique:App\Models\Customer',
]);
if ($validator->fails()) {
$errors = $validator->messages()->getMessages();
return Response()->json(['status' => false, 'message' => 'Something Went Wrong', 'response' => ['errors' => $errors]], 401);
};
// Get only email and name of the customer from request
$data = $request->only('name', 'email');
// Save Customer Data
$customer = CustomerServiceProvider::saveData($data);
if($customer){
// Send email to the request customer
CustomerServiceProvider::sendEmail($data);
return Response()->json(['status' => true, 'message' => 'Successfuly Inserted', 'response' => ['data' => $customer]], 200);
}
return Response()->json(['status' => false, 'message' => 'Something Went Wrong', 'response' => []], 401);
}
}
<?php
namespace App\Providers;
use App\Models\Customer;
use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeNewCustomer;
class CustomerServiceProvider {
public static function saveData($data)
{
$customer = new Customer();
$customer->name = $data['name'];
$customer->email = $data['email'];
return $customer->save() ? $customer : false;
}
public static function sendEmail($data)
{
Mail::to($data['email'])->send(new WelcomeNewCustomer());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment