*/ namespace Modules\MMFCustomersGroups\Http\Controllers; use Eventy; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use App\Email; use Modules\MMFCustomersGroups\Entities\Customer; use Modules\MMFCustomersGroups\Entities\CustomersGroup; class CustomersGroupsController extends Controller { public function list() { // Get the list of Mailboxes the current User is allowed to access. $user = auth()->user(); $mailboxes = $user->mailboxesIdsCanView(); // Get the list of Customers Groups, filtered by Mailbox. $groups = CustomersGroup ::whereIn('mailbox_id', $mailboxes) ->get(); return view('mmfcustomersgroups::groups/list', [ 'groups' => $groups, ]); } public function create() { // Get the list of Mailboxes the current User is allowed to access. $user = auth()->user(); $mailboxes = $user->mailboxesCanView(); // Get the list of Customers that can be attached to a group. $customers_query = Customer::with('emails'); // Set a hook so the query can be filtered by other modules. $customers_query = Eventy::filter('mmfcustomergroups.groups.create.customers-query', $customers_query); $customers = $customers_query->get(); // Get a list of Emails from the list of Customers. $emails = $customers ->pluck('emails') ->flatten() ->sortBy('email'); $group = new CustomersGroup(); return view('mmfcustomersgroups::groups/create', [ 'mailboxes' => $mailboxes, 'customers' => $customers, 'emails' => $emails, 'group' => $group, ]); } public function update() { // TODO } public function save(Request $request) { // Convert the list of Emails into a list of Customers. foreach ( $request->emails as $email_id ) { $email = Email::find($email_id); $customers[] = $email->customer; } // Drop duplicates from the list of Customers. $customers = collect($customers)->unique(); $customers_id = $customers->pluck('id'); $group = new CustomersGroup(); $group->name = $request->name; $group->mailbox_id = $request->mailbox; // Save early to set the Group id, before setting the relationships. $group->save(); $group->customers()->attach($customers_id); return $this->list(); } }