<?php
// 1) create a service class in: App/Services/DeleteEventService.php
<?php
namespace App\Services ;
use App\Registration;
use App\Mail\DeleteEvent;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
class DeleteEventService extends Controller {
public function __construct()
{
}
public function deleteEvent($event) {
$emails = [] ;
// get all registrations from this event date
$registrations = Registration::where( 'event_date', $event->event_date )->get() ;
// get all user emails registered to this event date
foreach( $registrations as $reg)
$emails[] = $reg->user->email;
// delete all entries from 'registrations' table that match this event
Registration::where('event_date', $event->event_date )->delete() ;
// delete the event
$event->delete() ;
// Mail admin and CC users that this event was deleted
Mail::to( 'juan@c-istudios.com' )
->cc($emails)
->send( new DeleteEvent( 'Cancelled Event', $event->event_date ) );
}
}
// 2) import these classes into our controller:
use App\Services\DeleteEventService;
// 2) Inject this service class into our method where it needs to be refactored
public function destroy(DeleteEventService $evtServ, $id) {
// find this event
$emails = [] ;
$event = Event::find($id) ;
// using Service class:
$evtServ->deleteEvent($event) ;
/* // ^^ Refactored to Service Class DeleteEventService loaded via dependency injection ^^
// get all registrations from this event date
$registrations = Registration::where( 'event_date', $event->event_date )->get() ;
// get all user emails registered to this event date
foreach( $registrations as $reg)
$emails[] = $reg->user->email;
// delete all entries from 'registrations' table that match this event
Registration::where('event_date', $event->event_date )->delete() ;
// delete the event
$event->delete() ;
// Mail admin and CC users that this event was deleted
Mail::to( 'juan@c-istudios.com' )
->cc($emails)
->send( new DeleteEvent( 'Cancelled Event', $event->event_date ) );
*/
Session::flash('success', 'Event Deleted');
return redirect()->back() ;
}
// Controller is now refactored.