*/ 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() { $group = new CustomersGroup(); return $this->update($group); } public function update(CustomersGroup $group) { // 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'); return view('mmfcustomersgroups::groups/edit', [ 'mailboxes' => $mailboxes, 'customers' => $customers, 'emails' => $emails, 'group' => $group, ]); } public function save(Request $request) { // Get the Customer Group that should be updated, // or create a new one. $group = ( $request->customer_id ) ? CustomersGroup::find($request->customer_id): new CustomersGroup(); $group->name = $request->name; $group->mailbox_id = $request->mailbox; // Save early to set the Group id, before setting the relationships. $group->save(); // 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->customers()->sync($customers_id); return $this->list(); } }