Example #1
0
 public function addTrainingData($user, $training)
 {
     $collection = new Collection();
     $visible = true;
     foreach ($training as $itemKey => $item) {
         $item['visible'] = $visible;
         foreach ($item['relations'] as $relationKey => $relation) {
             $done = true;
             foreach ($relation as $elementKey => $element) {
                 $element['id'] = "{$item['id']}.{$element['id']}";
                 $element['watch-url'] = route('training.watch', ['year' => 2016, 'item' => $element['id']]);
                 $element['watched'] = Watched::where('subscription_id', $user->id)->where('item_id', $element['id'])->first();
                 $element['visible'] = $visible || $element['watched'];
                 $done = $done && $element['watched'];
                 if ($relationKey == 'quiz') {
                     $element['answer'] = $element['watched'] ? $element['watched']->answer : null;
                 }
                 $visible = $element['watched'] !== null;
                 $item['relations'][$relationKey][$elementKey] = $element;
             }
         }
         $item['done'] = $done;
         $collection->push($item);
     }
     return $collection;
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $month = new Carbon($this->argument('month'));
     $billboards = Billboard::activated()->get();
     $pictures = Storage::files();
     $missing_pictures = new Collection();
     foreach ($billboards as $billboard) {
         $facings = $billboard->facings->all();
         foreach ($facings as $facing) {
             $ref = $this->reference($billboard, $facing, $month);
             $image_url = "{$ref}.jpg";
             if (in_array($image_url, $pictures)) {
                 try {
                     $this->trackingRepository->create(['facing_id' => $facing->id, 'image_url' => $image_url, 'tracking_date' => $month, 'location_id' => $billboard->location_id]);
                     $this->info('Tracking #' . $ref . ' with image url ' . $image_url . ' created successfully.');
                 } catch (\Illuminate\Database\QueryException $e) {
                     $this->error('Tracking #' . $ref . ' already exists.');
                 }
             } else {
                 $this->error('Facing #' . $ref . ' picture missing.');
                 $missing_pictures->push(["name" => $facing->name, "image_url" => $image_url]);
             }
         }
     }
     if (!$missing_pictures->isEmpty()) {
         $this->notifyMissingPictures($missing_pictures, "*****@*****.**");
     }
 }
 /**
  *
  * $newsletter
  */
 protected function getMaps()
 {
     $posts = new Collection();
     $projects = new Collection();
     $this->each(function ($widget) use($projects, $posts) {
         if ($widget->resource) {
             if ($widget->resource_type == Post::class) {
                 $posts->push($widget->resource_id);
             }
             if ($widget->resource_type == Project::class) {
                 $projects->push($widget->resource_id);
             }
         }
         if ($widget->other_resource) {
             if ($widget->other_resource_type == Post::class) {
                 $posts->push($widget->other_resource_id);
             }
             if ($widget->other_resource_type == Project::class) {
                 $projects->push($widget->other_resource_id);
             }
         }
     });
     $posts = Post::whereIn('posts.id', $posts->all())->with(['translations', 'images', 'images.sizes'])->get();
     $projects = Project::whereIn('portfolio_projects.id', $projects->all())->with(['translations', 'images', 'images.sizes'])->get();
     return [$posts, $projects];
 }
 /**
  * Display the specified resource.
  *
  * @param int|null $id
  *
  * @return \Illuminate\Http\Response
  */
 public function show($id = null)
 {
     if ($id === null) {
         $profile = Auth::user()->getProfile();
     } else {
         $profile = Profile::findOrFail($id);
     }
     $is_mine = $profile->user_id == \Flocc\Auth::getUserId();
     if ($is_mine === true) {
         $activities = (new Activities())->get();
         $tribes = (new Tribes())->get();
         $events_time_lines = new Collection();
         foreach ($profile->getTimeLine()->getLatestUpdatedEvents() as $event) {
             foreach ($event->getTimeLine() as $line) {
                 if ($line->isMessage()) {
                     $events_time_lines->push(['id' => $event->getId(), 'slug' => $event->getSlug(), 'event' => $event->getTitle(), 'date' => $line->getTime(), 'message' => $line->getMessage()]);
                 }
             }
         }
         $events_time_lines = $events_time_lines->sortByDesc('date')->slice(0, 5);
         return view('dashboard', compact('profile', 'is_mine', 'activities', 'tribes', 'events_time_lines'));
     } else {
         return view('profiles.show', compact('profile', 'is_mine', 'id'));
     }
 }
Example #5
0
 public function maps($tournament)
 {
     $maps = new Collection();
     $this->reports($tournament)->get()->each(function ($report) use(&$maps) {
         $maps->push(Map::find($report->map));
     });
     return $maps;
 }
Example #6
0
 public function fire()
 {
     $pushWords = new Collection();
     $dayWord = WordCard::find(Setting::first()->word_id);
     $pushWords->push(['word_id' => $dayWord->id, 'category_id' => $dayWord->category_id]);
     Category::all()->each(function ($category) use($pushWords) {
         $this->info("looking at category {$category->id}");
         $word = $this->getSentWord($category);
         if ($word) {
             $pushWords->push(['word_id' => $word->id, 'category_id' => $category->id]);
         } else {
             $this->error('Empty category');
         }
     });
     $this->check();
     $this->pushWords2($pushWords);
 }
Example #7
0
 /**
  * @return Collection
  */
 public function routes()
 {
     $routes = new Collection();
     foreach ($this->items as $module) {
         foreach ($module->routes as $route) {
             $routes->push($route);
         }
     }
     return $routes;
 }
 private function sortByLikes(Collection $collection, Collection $orderArray)
 {
     $sorted = new Collection();
     $orderArray->each(function ($orderElem) use($collection, $sorted) {
         if ($collection->contains($orderElem->likeable_id)) {
             $sorted->push($collection->find($orderElem->likeable_id));
         }
     });
     return $sorted;
 }
 public function testSerializeNested()
 {
     $obj = new RESTModelStub();
     $fooobj = new RESTModelStub();
     $fooobj->foo = 'bar';
     $collection = new Collection();
     $collection->push($fooobj);
     $obj->setRelation('foos', $collection);
     $serializer = new BaseSerializer();
     $this->assertEquals(array('fred' => array('foos' => array(array('foo' => 'bar')))), $serializer->serialize($obj, 'fred'));
 }
Example #10
0
 public function getDashboard()
 {
     $favorites = Favorite::whereUserId(Auth::user()->id)->get();
     $collection = new Collection();
     foreach ($favorites as $favorite) {
         $content = new Content('layout_movie');
         $object = $content->wherePageId($favorite->page_id)->whereContentIdentifier($favorite->content_identifier)->first();
         if ($object) {
             $collection->push($object);
         }
     }
     return $collection;
 }
 public function testOverrideLink()
 {
     Config::shouldReceive('get')->with('andizzle/rest-framework::page_limit')->andReturn('5');
     REST::shouldReceive('getApiPrefix')->andReturn('api/v1');
     $obj = new RESTModelStub();
     $fooobj = new RESTModelStub();
     $fooobj->id = 1;
     $fooobj->root = 'roots';
     $collection = new Collection();
     $obj->setSideLoads(array('foos'));
     $collection->push($fooobj);
     $obj->setRelation('foos', $collection);
     $serializer = new HyperlinkedJSONSerializer();
     $serializer->setURLOverrides(array('foos' => 'fredId=1'));
     $this->assertEquals(array('fred' => array('links' => array('foos' => 'api/v1/roots?fredId=1'))), $serializer->serialize($obj, 'fred'));
 }
Example #12
0
 public function getHome()
 {
     $services = \App\Service::all();
     $categories = \Auth::user()->categories;
     $servicesnp = new Collection();
     foreach ($services as $service) {
         $service->name = '(' . $service->category->name . ')-' . $service->name;
     }
     foreach ($categories as $category) {
         foreach ($category->services as $service) {
             $service->name = '(' . $service->category->name . ')-' . $service->name;
             $servicesnp->push($service);
         }
     }
     return view('pages.home', compact('services', 'servicesnp'));
 }
 public function testSerializeNoEmbed()
 {
     Config::shouldReceive('get')->with('andizzle/rest-framework::page_limit')->andReturn('5');
     Config::shouldReceive('get')->with('andizzle/rest-framework::serializer.embed-relations')->once()->andReturn(false);
     $obj = new RESTModelStub();
     $obj->foo = 'bar';
     $fooobj = new RESTModelStub();
     $fooobj->id = 1;
     $fooobj->root = 'roots';
     $collection = new Collection();
     $obj->setSideLoads(array('foos'));
     $collection->push($fooobj);
     $obj->setRelation('foos', $collection);
     $serializer = new JSONSerializer();
     $this->assertEquals(array('fred' => array('foo' => 'bar', 'foos' => array('1'))), $serializer->serialize($obj, 'fred'));
 }
Example #14
0
 public function run()
 {
     foreach ([1, 2] as $account) {
         $teller = 0;
         $teams = new Collection();
         while ($teller < 3) {
             $teams->push(Team::create(['account_id' => $account, 'nl' => ['name' => $this->faker->sentence(2), 'description' => $this->faker->paragraph(5)], 'en' => ['name' => $this->faker->sentence(2), 'description' => $this->faker->paragraph(5)], 'fr' => ['name' => $this->faker->sentence(2), 'description' => $this->faker->paragraph(5)], 'de' => ['name' => $this->faker->sentence(2), 'description' => $this->faker->paragraph(5)]]));
             $teller++;
         }
         $account = Account::find($account);
         $teams = array_flip($teams->lists('id')->toArray());
         foreach ($account->memberships as $membership) {
             $membership->teams()->attach(array_rand($teams, rand(1, 3)));
         }
     }
 }
Example #15
0
 /**
  *
  */
 public function save()
 {
     if (empty($this->data)) {
         return;
     }
     if ($this->relation instanceof Relations\HasMany && is_array($this->data)) {
         if (is_numeric($this->data[0])) {
             $data = new Collection();
             foreach ($this->data as $key => $item) {
                 // $this->data[$key] = $this->related->baseModel->find($item);
                 $data->push($this->related->baseModel->find($item));
             }
         } else {
             $data = new Collection($this->data);
         }
         // detach any existing models and only save the selected ones
         $foreignKey = $this->relation->getPlainForeignKey();
         $current = $this->relation->getResults();
         if (!$current) {
             $this->relation->saveMany($data->toArray());
             return;
         }
         $all = $data->merge($current);
         foreach ($all as $item) {
             if ($keep = $data->find($item->getKey())) {
                 $this->relation->save($keep);
             } else {
                 $item->{$foreignKey} = null;
                 $item->save();
             }
         }
     } else {
         if ($this->relation instanceof Relations\BelongsToMany && is_array($this->data)) {
             if (is_numeric($this->data[0])) {
                 $this->relation->sync($this->data);
             }
         } else {
             /* If we have an id let's grab the model instance, otherwise assume we were given it */
             $this->data = is_numeric($this->data) ? $this->related->baseModel->find($this->data) : $this->data;
             parent::saveRelation($this->relation, $this->data);
         }
     }
 }
 public function testItSetsTheCategoryAsTrashedForTheSelections()
 {
     $category = factory(Category::class)->create();
     $account = factory(Account::class)->create();
     $brand = factory(Brand::class)->create();
     $selections = new Collection();
     $products = factory(Product::class)->times(2)->create(['account_id' => $account->id, 'brand_id' => $brand->id])->each(function ($product) use($selections, $account, $category, $brand) {
         $product->categories()->attach($category);
         $selection = factory(ProductSelection::class)->create(['account_id' => $account->id, 'brand_id' => $brand->id, 'product_id' => $product->id]);
         factory(ProductCategorySelection::class)->create(['selection_id' => $selection->id, 'category_id' => $category->id]);
         $selections->push($selection);
     });
     $job = new BatchGammaDeactivation($category, $account, $brand);
     $job->handle(app(ProductSelection::class));
     foreach ($selections as $selection) {
         $count = app('db')->table('product_gamma_categories')->where(['selection_id' => $selection->id, 'category_id' => $category->id])->whereNotNull('deleted_at')->count();
         $this->assertSame(1, $count);
     }
 }
 protected function create($request, $response, $args)
 {
     $data = $request->getParsedBody();
     $uri = $request->getUri();
     $files = $request->getUploadedFiles();
     array_walk_recursive($files, function ($v, $k) use($files) {
         if ($v instanceof UploadedFile) {
             $files[] = $v;
         }
     });
     $collection = new Collection();
     foreach ($files as $file) {
         if ($file->getError() === UPLOAD_ERR_OK) {
             $f = File::create(['name' => ucfirst($file->getClientFilename()), 'filename' => $file->getClientFilename(), 'filetype' => $file->getClientMediaType(), 'filesize' => $file->getSize(), 'url' => $uri->getScheme() . '://' . $uri->getHost() . '/media/' . $file->getClientFilename(), 'download' => false]);
             $collection->push($f);
             $file->moveTo($this->settings['mediaDir'] . $file->getClientFilename());
         }
     }
     return $response->write($collection->toJson());
 }
Example #18
0
 public static function organizarSemana($horarios_disponibles, $profesor_id, $cant, $ciclo_id)
 {
     $ciclo = Ciclo::find($ciclo_id);
     $horarios_gral = Horario::all();
     $horarios_ocupados = Horario::select('horarios.*')->distinct()->join('clases', 'clases.horario_id', '=', 'horarios.id')->join('grupos', 'grupos.id', '=', 'clases.grupo_id')->where('profesor_id', '=', $profesor_id)->where('ciclo_id', '=', $ciclo->id)->get();
     $horarios_profesor = $horarios_gral->diff($horarios_ocupados);
     $horarios = $horarios_disponibles->intersect($horarios_profesor);
     $semana = new Collection();
     while ($cant > 0) {
         for ($i = 0; $i < 5 && $cant > 0; $i++) {
             foreach ($horarios as $key => $horario) {
                 if ($horario->dia == Horario::$dias[$i]) {
                     $semana->push($horarios->pull($key));
                     $cant--;
                     break;
                 }
             }
         }
     }
     return $semana;
 }
Example #19
0
 public function getUsers(Request $request)
 {
     $lat = $request->get('lat');
     $long = $request->get('long');
     $schools = School::all();
     $users = new \Illuminate\Database\Eloquent\Collection();
     for ($i = 0; $i < $schools->count(); $i++) {
         $schoolLat = $schools->get($i)->latitude;
         $schoolLong = $schools->get($i)->longitude;
         if ($this->haversine($lat, $long, $schoolLat, $schoolLong) < 50) {
             $users->push($schools->get($i)->usersNotVoted($request->get('CurrentUser')->id));
         }
     }
     return Response::json(['users' => $users->collapse()], 200);
 }
 /**
  * Campaign Listing AjaxHandler With Filter
  * @param Request $request
  * @param $method
  * @return mixed
  * @throws \Exception
  * @author: Vini Dubey<*****@*****.**>
  * @since: xx-xx-xxxx
  */
 public function campaignListAjaxHandler(Request $request, $method)
 {
     $inputData = $request->input();
     $objCategoryModel = ProductCategory::getInstance();
     $objCampaignModel = Campaigns::getInstance();
     $objProductModel = Products::getInstance();
     $supplierId = Session::get('fs_supplier')['id'];
     switch ($method) {
         case 'manageDailyspecial':
             //   Modify code for filter //
             $iTotalRecords = $iDisplayLength = intval($_REQUEST['length']);
             $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength;
             $iDisplayStart = intval($_REQUEST['start']);
             $sEcho = intval($_REQUEST['draw']);
             //                $columns = array('o.order_id', 'o.added_date', 'customer_email', 'product_name', 'o.finalprice', 't.tx_type', 'o.order_status');
             $columns = array('campaigns.campaign_id', 'campaigns.campaign_name', 'campaigns.campaign_type', 'users.username', 'campaigns.discount_value', 'campaigns.available_from', 'available_upto', 'category', 'product', 'campaigns.campaign_status');
             $sortingOrder = "";
             if (isset($_REQUEST['order'])) {
                 $sortingOrder = $columns[$_REQUEST['order'][0]['column']];
             }
             if (isset($_REQUEST["customActionType"]) && $_REQUEST["customActionType"] == "group_action") {
                 if ($_REQUEST['customActionValue'] != '' && !empty($_REQUEST['campaignId'])) {
                     //                        $statusData = array('campaign_status' => $_REQUEST['customActionValue']);
                     $statusData['campaign_status'] = $_REQUEST['customActionValue'];
                     $whereForStatusUpdate = ['rawQuery' => 'campaign_id IN (' . implode(',', $_REQUEST['campaignId']) . ')'];
                     //                        $statusData = ['rawQuery' => 'campaign_id= ?', 'bindParams' => [$_REQUEST['customActionValue']]];
                     $updateResult = $objCampaignModel->updateFlashsaleStatus($statusData, $whereForStatusUpdate);
                     if ($updateResult) {
                         //NOTIFICATION TO USER FOR ORDER STATUS CHANGE
                         $records["customActionStatus"] = "OK";
                         // pass custom message(useful for getting status of group actions)
                         $records["customActionMessage"] = "Group action successfully has been completed.";
                         // pass custom message(useful for getting status of group actions)
                     }
                 }
             }
             // End Modify code for filter//
             $where = ['rawQuery' => 'campaign_type IN(1,2) AND by_user_id = ? AND campaign_status IN(1,2,3,4,5)', 'bindParams' => [$supplierId]];
             $selectedColumn = ['campaigns.*', 'users.username'];
             $dailyspecialInfo = $objCampaignModel->getAllFlashsaleDetails($where, $selectedColumn);
             foreach ($dailyspecialInfo as $flashkey => $flashval) {
                 //                    $categoryIds = $flashval->for_category_ids;
                 $productIds = $flashval->for_product_ids;
                 //                    $where = ['rawQuery' => 'category_id IN(' . $categoryIds . ')'];
                 //                    $getcategory = $objCategoryModel->getCategoryNameById($where);
                 $whereProd = ['rawQuery' => 'product_id IN(' . $productIds . ')'];
                 $selectedColumn = [DB::raw('GROUP_CONCAT(DISTINCT product_name) AS product_name'), DB::raw('GROUP_CONCAT(DISTINCT product_id) AS product_id')];
                 $getproduct = $objProductModel->getProductNameById($whereProd, $selectedColumn);
                 //                    foreach ($getcategory as $catkey => $catval) {
                 //                        $dailyspecialInfo[$flashkey]->category = $catval->category_name;
                 //                    }
                 foreach ($getproduct as $prodkey => $prodval) {
                     $dailyspecialInfo[$flashkey]->product = $prodval->product_name;
                 }
             }
             $flash = json_decode(json_encode($dailyspecialInfo), true);
             $flashDetail = new Collection();
             foreach ($flash as $mainflashkey => $mainflashval) {
                 $flashDetail->push(['checkbox' => '<input type="checkbox" name="id[]" value="' . $mainflashval['campaign_id'] . '">', 'campaign_id' => $mainflashval['campaign_id'], 'campaign_name' => $mainflashval['campaign_name'], 'campaign_type' => $mainflashval['campaign_type'] == 1 ? 'Dailyspecial' : 'Flashsale', 'username' => $mainflashval['username'], 'discount_value' => $mainflashval['discount_value'] . '%', 'available_from' => date('d F Y - h:i A', $mainflashval['available_from']), 'available_upto' => date('d F Y - h:i A', $mainflashval['available_upto']), 'product' => count(explode(",", $mainflashval['product'])), 'campaign_status' => $mainflashval['campaign_status'], 'action' => '', 'supplierId' => Session::get('fs_supplier')['id']]);
             }
             //FILTERING START FROM HERE //
             $filteringRules = '';
             if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'filter' && $_REQUEST['action'][0] != 'filter_cancel') {
                 if ($_REQUEST['campaign_id'] != '') {
                     $filteringRules[] = "(`campaigns`.`campaign_id` = " . $_REQUEST['campaign_id'] . " )";
                 }
                 if ($_REQUEST['campaign_name'] != '') {
                     $filteringRules[] = "(`campaigns`.`campaign_name` LIKE '%" . $_REQUEST['campaign_name'] . "%' )";
                 }
                 if ($_REQUEST['campaign_type'] != '') {
                     $filteringRules[] = "(`campaigns`.`campaign_type` = " . $_REQUEST['campaign_type'] . " )";
                 }
                 if ($_REQUEST['username'] != '') {
                     $filteringRules[] = "(`users`.`username` LIKE '%" . $_REQUEST['username'] . "%' )";
                 }
                 if ($_REQUEST['discount_value_from'] != '' && $_REQUEST['discount_value_to'] != '') {
                     $filteringRules[] = "(`campaigns`.`discount_value` BETWEEN " . intval($_REQUEST['discount_value_from']) . " AND " . intval($_REQUEST['discount_value_to']) . "  )";
                 }
                 if ($_REQUEST['available_from_date'] != '' && $_REQUEST['available_upto_date'] != '') {
                     $filteringRules[] = "( `campaigns`.`available_from` < " . strtotime(str_replace('-', ' ', $_REQUEST['available_upto_date'])) . " AND `campaigns`.`available_upto` > " . strtotime(str_replace('-', ' ', $_REQUEST['available_from_date'])) . " )";
                 }
                 //                    print_a($filteringRules);
                 //                    elseif ($_REQUEST['available_from_date'] != '') {
                 ////                        $filteringRules[] = "(`campaigns`.`available_from` BETWEEN " . strtotime($_REQUEST['available_from_date']) . " AND  `campaigns`.`available_upto` = " . strtotime($_REQUEST['available_upto_date']) . "  )";
                 //                        $filteringRules[] = "(`campaigns`.`available_from` = " . $_REQUEST['available_from_date'] . ")";
                 ////                        $filteringRules[] = "(`campaigns`.`available_from` = " . strtotime((str_replace( '-',' ',$_REQUEST['available_from_date']))) . ")";
                 ////                        $filteringRules[] = "(`campaigns`.`available_from` BETWEEN " . strtotime(str_replace( '-',' ',$_REQUEST['available_from_date'])) . " AND " . strtotime(str_replace( '-',' ',$_REQUEST['available_upto_date'])) . "  )";
                 ////                        $filteringRules[] = "(`campaigns`.`available_upto` BETWEEN " . strtotime(str_replace( '-',' ',$_REQUEST['available_from_date'])) . " AND  " . strtotime(str_replace( '-',' ',$_REQUEST['available_upto_date'])) . "  )";
                 //                    } elseif($_REQUEST['available_upto_date'] != ''){
                 //                        $filteringRules[] = "(`campaigns`.`available_upto` LIKE '%" . strtotime(str_replace( '-',' ',$_REQUEST['available_upto_date'])) . "%')";
                 //                    }
                 //                    if ($_REQUEST['category_id'] != '') {
                 //                        $filteringRules[] = "(`campaigns`.`for_category_ids`  LIKE '%" . implode(",", $_REQUEST['category_id']) . "%' )";
                 //                    }
                 if ($_REQUEST['campaign_status'] != '') {
                     $filteringRules[] = "(`campaigns`.`campaign_status` = " . $_REQUEST['campaign_status'] . " )";
                 }
                 // FOR CAMPAIGN FILTER //
                 $implodedWhere = '';
                 if (!empty($filteringRules)) {
                     $implodedWhere = implode(' AND ', array_map(function ($filterValues) {
                         return $filterValues;
                     }, $filteringRules));
                 }
                 $where = ['rawQuery' => 'campaign_type IN(1,2) AND by_user_id = ? AND campaign_status IN(1,2,3,4,5)', 'bindParams' => [$supplierId]];
                 $selectedColumn = ['campaigns.*', 'users.username'];
                 $MainFlashInfo = $objCampaignModel->getAllFlashDetail($where, $implodedWhere, $sortingOrder, $iDisplayLength, $iDisplayStart, $selectedColumn);
                 foreach ($MainFlashInfo as $flashkey => $flashval) {
                     //                        $categoryIds = $flashval->for_category_ids;
                     $productIds = $flashval->for_product_ids;
                     //                        $where = ['rawQuery' => 'category_id IN(' . $categoryIds . ')'];
                     //                        $getcategory = $objCategoryModel->getCategoryNameById($where);
                     $whereProd = ['rawQuery' => 'product_id IN(' . $productIds . ')'];
                     $selectedColumn = [DB::raw('GROUP_CONCAT(DISTINCT product_name) AS product_name'), DB::raw('GROUP_CONCAT(DISTINCT product_id) AS product_id')];
                     $getproduct = $objProductModel->getProductNameById($whereProd, $selectedColumn);
                     //                        foreach ($getcategory as $catkey => $catval) {
                     //                            $MainFlashInfo[$flashkey]->category = $catval->category_name;
                     //                        }
                     foreach ($getproduct as $prodkey => $prodval) {
                         $MainFlashInfo[$flashkey]->product = $prodval->product_name;
                     }
                 }
                 // FOR DISPLAYING DATA TO DATATABLE //
                 $flash = json_decode(json_encode($MainFlashInfo), true);
                 $flashDetail = new Collection();
                 foreach ($flash as $mainflashkey => $mainflashval) {
                     $flashDetail->push(['checkbox' => '<input type="checkbox" name="id[]" value="' . $mainflashval['campaign_id'] . '">', 'campaign_id' => $mainflashval['campaign_id'], 'campaign_name' => $mainflashval['campaign_name'], 'campaign_type' => $mainflashval['campaign_type'] == 1 ? 'Dailyspecial' : 'Flashsale', 'username' => $mainflashval['username'], 'discount_value' => $mainflashval['discount_value'] . '%', 'available_from' => date('d F Y - h:i A', $mainflashval['available_from']), 'available_upto' => date('d F Y - h:i A', $mainflashval['available_upto']), 'product' => count(explode(",", $mainflashval['product'])), 'campaign_status' => $mainflashval['campaign_status'], 'action' => '', 'supplierId' => Session::get('fs_supplier')['id']]);
                 }
                 // FOR SHOWING STATUS AND EDIT HTML //
                 //                    foreach ($MainFlashInfo as $ORkey => $ORvalue) {
                 //                        $paymentType = $ORvalue->campaign_status == 1 ? 'Active' : 'Inactive';
                 //                        $records["data"][] = array(
                 //                            '<span class="tooltips" title="Edit Wholesale Details." data-placement="top"> <a href="/supplier/edit-wholesale/' . $ORvalue->campaign_id . '" class="btn btn-sm grey-cascade" style="margin-left: 10%;">
                 //                                                    <i class="fa fa-pencil-square-o"></i>
                 //                                                </a>
                 //                                            </span>',
                 //                            '<td style="text-align: center"><button class="btn ' . (($ORvalue->campaign_status == 1) ? "btn-success" : "btn-danger") . ' wholesale-status" data-id="' . $ORvalue->campaign_id . '" data-set-by="' . $supplierId . '">' . (($ORvalue->campaign_status == 1) ? 'Active' : 'Inactive') . ' </button></td>',
                 //                        );
                 //                    }
             }
             //FILTERING ENDS HERE //
             $status_list = array(1 => array("success" => "Success"), 2 => array("primary" => "InActive"), 3 => array("warning" => "Rejected"), 4 => array("danger" => "Deleted"), 5 => array("danger" => "Finished"));
             return Datatables::of($flashDetail, $status_list)->addColumn('action', function ($flashDetail) {
                 return '<span class="tooltips" title="Edit Campaign Details." data-placement="top"> <a href="/supplier/edit-campaign/' . $flashDetail['campaign_id'] . '" class="btn btn-sm grey-cascade" style="margin-left: 10%;">
                                                 <i class="fa fa-pencil-square-o"></i>
                                             </a>
                                         </span>';
                 //                                            <span class="tooltips" title="Delete campaign Details." data-placement="top"> <a href="#" data-cid="' . $flashDetail['campaign_id'] . '" class="btn btn-danger delete-dailyspecial" style="margin-left: 10%;">
                 //                                                    <i class="fa fa-trash-o"></i>
                 //                                                </a>
                 //                                            </span>
             })->addColumn('campaign_status', function ($flashDetail) use($status_list) {
                 return '<span class="label label-sm label-' . key($status_list[$flashDetail['campaign_status']]) . '">' . current($status_list[$flashDetail['campaign_status']]) . '</span>';
             })->removeColumn('for_shop_id')->removeColumn('campaign_banner')->make();
             break;
         default:
             break;
     }
 }
 public function productListAjaxHandler(Request $request, $method)
 {
     $inputData = $request->input();
     $objModelProducts = Products::getInstance();
     $objCategoryModel = ProductCategory::getInstance();
     $supplierId = Session::get('fs_supplier')['id'];
     switch ($method) {
         case 'manageProducts':
             //   Modify code for filter //
             $iTotalRecords = $iDisplayLength = intval($_REQUEST['length']);
             $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength;
             $iDisplayStart = intval($_REQUEST['start']);
             $sEcho = intval($_REQUEST['draw']);
             //                $columns = array('o.order_id', 'o.added_date', 'customer_email', 'product_name', 'o.finalprice', 't.tx_type', 'o.order_status');
             $columns = array('products.product_id', 'products.added_date', 'products.product_type', 'users.username', 'shops.shop_name', 'products.product_name', 'products.price_total', 'products.list_price', 'products.min_qty', 'products.max_qty', 'products.category_id', 'products.available_countries', 'products.products_status');
             $sortingOrder = "";
             if (isset($_REQUEST['order'])) {
                 $sortingOrder = $columns[$_REQUEST['order'][0]['column']];
             }
             if (isset($_REQUEST["customActionType"]) && $_REQUEST["customActionType"] == "group_action") {
                 if ($_REQUEST['customActionValue'] != '' && !empty($_REQUEST['productId'])) {
                     $statusData['product_status'] = $_REQUEST['customActionValue'];
                     $whereForStatusUpdate = ['rawQuery' => 'product_id IN (' . implode(',', $_REQUEST['productId']) . ')'];
                     $updateResult = $objModelProducts->updateProductWhere($statusData, $whereForStatusUpdate);
                     if ($updateResult) {
                         //NOTIFICATION TO USER FOR ORDER STATUS CHANGE
                         $records["customActionStatus"] = "OK";
                         // pass custom message(useful for getting status of group actions)
                         $records["customActionMessage"] = "Group action successfully has been completed.";
                         // pass custom message(useful for getting status of group actions)
                     }
                 }
             }
             // End Modify code for filter//
             // NORMAL DATATABLE CODE STARTS//
             $where = ['rawQuery' => 'products.product_type = ? AND products.product_status IN (0,1,2,3,4) AND product_images.image_type = ?', 'bindParams' => [0, 0]];
             $selectedColumn = ['products.*', 'users.username', 'users.role', 'shops.shop_name', 'product_categories.category_name', 'product_images.image_url'];
             $getAllProducts = $objModelProducts->getAllProducts($where, $selectedColumn);
             $productInfo = json_decode(json_encode($getAllProducts), true);
             $products = new Collection();
             foreach ($productInfo as $key => $val) {
                 $products->push(['checkbox' => '<input type="checkbox" name="id[]" value="' . $val['product_id'] . '">', 'product_id' => $val['product_id'], 'product_images' => '<img src="' . $val['image_url'] . '" width="30px">', 'added_date' => date('d-F-Y', $val['added_date']), 'shop_name' => $val['shop_name'], 'product_name' => $val['product_name'], 'price_total' => $val['price_total'], 'list_price' => $val['list_price'], 'min_qty' => $val['min_qty'], 'max_qty' => $val['max_qty'], 'category_name' => $val['category_name'], 'in_stock' => $val['in_stock'], 'username' => $val['username'], 'available_countries' => $val['available_countries'], 'product_status' => $val['product_status']]);
             }
             // FILTERING STARTS FROM HERE //
             $filteringRules = '';
             if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'filter' && $_REQUEST['action'][0] != 'filter_cancel') {
                 if ($_REQUEST['product_id'] != '') {
                     $filteringRules[] = "(`products`.`product_id` = " . $_REQUEST['product_id'] . " )";
                 }
                 if ($_REQUEST['date_from'] != '' && $_REQUEST['date_to'] != '') {
                     $filteringRules[] = "(`products`.`added_date` BETWEEN " . strtotime(str_replace('-', ' ', $_REQUEST['date_from'])) . " AND " . strtotime(str_replace('-', ' ', $_REQUEST['date_to'])) . "  )";
                 }
                 if ($_REQUEST['store_name'] != '') {
                     $filteringRules[] = "(`shops`.`shop_name` LIKE '%" . $_REQUEST['store_name'] . "%' )";
                 }
                 if ($_REQUEST['product_name'] != '') {
                     $filteringRules[] = "(`products`.`product_name` LIKE '%" . $_REQUEST['product_name'] . "%' )";
                 }
                 if ($_REQUEST['price_from'] != '' && $_REQUEST['price_to'] != '') {
                     $filteringRules[] = "(`products`.`price_total` BETWEEN " . intval($_REQUEST['price_from']) . " AND " . intval($_REQUEST['price_to']) . "  )";
                 }
                 if ($_REQUEST['list_price_from'] != '' && $_REQUEST['list_price_to'] != '') {
                     $filteringRules[] = "(`products`.`list_price` BETWEEN " . intval($_REQUEST['list_price_from']) . " AND " . intval($_REQUEST['list_price_to']) . "  )";
                 }
                 if ($_REQUEST['minimum_quantity'] != '') {
                     $filteringRules[] = "( `products`.`min_qty` = " . intval($_REQUEST['minimum_quantity']) . ")";
                 }
                 if ($_REQUEST['maximum_quantity'] != '') {
                     $filteringRules[] = "(`products`.`max_qty` = " . intval($_REQUEST['maximum_quantity']) . ")";
                 }
                 if ($_REQUEST['product_categories'] != '') {
                     $filteringRules[] = "(`products`.`category_id` = " . $_REQUEST['product_categories'] . " )";
                 }
                 if ($_REQUEST['added_by'] != '') {
                     $filteringRules[] = "(`users`.`username` LIKE '%" . $_REQUEST['added_by'] . "%' )";
                 }
                 if ($_REQUEST['product_status'] != '') {
                     $filteringRules[] = "(`products`.`product_status` = " . $_REQUEST['product_status'] . " )";
                 }
                 //print_a($filteringRules);
                 // Filter Implode //
                 $implodedWhere = '';
                 if (!empty($filteringRules)) {
                     $implodedWhere = implode(' AND ', array_map(function ($filterValues) {
                         return $filterValues;
                     }, $filteringRules));
                 }
                 if (!empty($implodedWhere)) {
                     $where = ['rawQuery' => 'products.product_type = ? AND products.product_status IN (0,1,2,3,4) AND product_images.image_type = ?', 'bindParams' => [0, 0]];
                     $selectedColumn = ['products.*', 'users.username', 'users.role', 'shops.shop_name', 'product_categories.category_name', 'product_images.image_url'];
                     $getAllFilterProducts = $objModelProducts->getAllFilterProducts($where, $implodedWhere, $sortingOrder, $iDisplayLength, $iDisplayStart, $selectedColumn);
                     $productFilter = json_decode(json_encode($getAllFilterProducts), true);
                     $products = new Collection();
                     foreach ($productFilter as $key => $val) {
                         $products->push(['checkbox' => '<input type="checkbox" name="id[]" value="' . $val['product_id'] . '">', 'product_id' => $val['product_id'], 'product_images' => '<img src="' . $val['image_url'] . '" width="80px">', 'added_date' => date('d-F-Y', $val['added_date']), 'shop_name' => $val['shop_name'], 'product_name' => $val['product_name'], 'price_total' => $val['price_total'], 'list_price' => $val['list_price'], 'min_qty' => $val['min_qty'], 'max_qty' => $val['max_qty'], 'category_name' => $val['category_name'], 'in_stock' => $val['in_stock'], 'username' => $val['username'], 'available_countries' => $val['available_countries'], 'product_status' => $val['product_status']]);
                     }
                 }
             }
             $status_list = array(0 => array("warning" => "Pending"), 1 => array("success" => "Success"), 2 => array("primary" => "InActive"), 3 => array("warning" => "Rejected"), 4 => array("danger" => "Deleted"), 5 => array("danger" => "Finished"));
             return Datatables::of($products, $status_list)->addColumn('action', function ($products) {
                 $action = '<div role="group" class="btn-group "> <button aria-expanded="false" data-toggle="dropdown" class="btn btn-default dropdown-toggle" type="button"> <i class="fa fa-cog"></i>&nbsp; <span class="caret"></span></button>';
                 $action .= '<ul role="menu" class="dropdown-menu">';
                 $action .= '<li><a href="/admin/edit-supplier/' . $products['product_id'] . '"><i class="fa fa-pencil" data-id="{{$products->product_id}}"></i>&nbsp;Edit</a></li>';
                 $action .= '<li><a href="javascript:void(0);" class="delete-product" data-cid="' . $products['product_id'] . '"><i class="fa fa-trash"></i>&nbsp;Delete</a></li>';
                 $action .= '</ul>';
                 $action .= '</div>';
                 return $action;
             })->addColumn('product_status', function ($products) use($status_list) {
                 return '<span class="label label-sm label-' . key($status_list[$products['product_status']]) . '">' . current($status_list[$products['product_status']]) . '</span>';
             })->make();
             // NORMAL DATATABLE CODE END'S HERE//
             break;
     }
 }
Example #22
0
 /**
  * Gets the player vehicle stats
  * @return array
  */
 public function getVehicleStats()
 {
     // Generate URI for request
     $uri = sprintf($this->uris[$this->game]['vehicles'], $this->game, $this->personaID);
     // Send request
     $results = $this->sendRequest($uri)['data'];
     // Create vehicles array
     $vehicles = new Collection();
     foreach ($results['mainVehicleStats'] as $vehicle) {
         $vehicles->push(['slug' => $vehicle['slug'], 'code' => $vehicle['code'], 'category' => $vehicle['category'], 'kills' => $vehicle['kills'], 'score' => array_key_exists('score', $vehicle) ? $vehicle['score'] : null, 'timeEquipped' => $vehicle['timeIn'], 'serviceStars' => $vehicle['serviceStars'], 'kpm' => MainHelper::divide($vehicle['kills'], MainHelper::divide($vehicle['timeIn'], 60))]);
     }
     return $vehicles;
 }
 public function flashsaleAjaxHandler(Request $request)
 {
     $inputData = $request->input();
     $method = $inputData['method'];
     $objCategoryModel = ProductCategory::getInstance();
     $objCampaignModel = Campaigns::getInstance();
     switch ($method) {
         case 'getActiveCategories':
             $where = ['rawQuery' => 'category_status = ? AND parent_category_id = ?', 'bindParams' => [1, 0]];
             $selectedColumn = ['category_id', 'category_name', 'category_status', 'for_shop_id'];
             $allactivecategories = $objCategoryModel->getAllMainCategories($where, $selectedColumn);
             if (!empty($allactivecategories)) {
                 echo json_encode($allactivecategories);
             } else {
                 echo 0;
             }
             break;
         case 'getSubCategoriesForMainCategory':
             $where = ['rawQuery' => 'category_status = ?', 'bindParams' => [1]];
             //                $selectedColumn = [DB::raw('SELECT product_categories.*
             //                CASE WHEN (parent_category_id == 0)
             //                 THEN DB::raw("GROUP_CONCAT(category_name)AS main_category_name")
             //                 END ')];
             $selectedColumn = ['product_categories.*', DB::raw('GROUP_CONCAT(category_id)AS main_category_id'), DB::raw('GROUP_CONCAT(category_name)AS main_category_name')];
             $allActiveSubcategories = $objCategoryModel->getSubCategoriesForMaincategory($where, $selectedColumn);
             $mainCategory = array_filter(array_map(function ($category) {
                 if ($category->parent_category_id == 0) {
                     return $category;
                 }
             }, $allActiveSubcategories))[0];
             $finalCatData = [];
             foreach (explode(',', $mainCategory->main_category_id) as $index => $mainCatID) {
                 foreach ($allActiveSubcategories as $subCatKey => $allActiveSubcategory) {
                     if ($allActiveSubcategory->parent_category_id == $mainCatID) {
                         $allActiveSubcategory->main_cat_name = explode(',', $mainCategory->main_category_name)[$index];
                         $finalCatData[$mainCatID] = $allActiveSubcategory;
                     }
                 }
             }
             if (!empty($finalCatData)) {
                 echo json_encode($finalCatData);
             } else {
                 echo 0;
             }
             break;
         case 'manageFlashsale':
             $where = ['rawQuery' => 'campaign_type = ?', 'bindParams' => [2]];
             $selectedColumn = ['campaigns.*', 'users.username'];
             $flashsaleInfo = $objCampaignModel->getAllFlashsaleDetails($where, $selectedColumn);
             foreach ($flashsaleInfo as $flashkey => $flashval) {
                 $categoryIds = $flashval->for_category_ids;
                 $where = ['rawQuery' => 'category_id IN(' . $categoryIds . ')'];
                 $getcategory = $objCategoryModel->getCategoryNameById($where);
                 foreach ($getcategory as $catkey => $catval) {
                     $flashsaleInfo[$flashkey]->category = $catval->category_name;
                 }
             }
             $flash = json_decode(json_encode($flashsaleInfo), true);
             //                echo'<pre>';print_r($flash);die("df");
             $flashDetail = new Collection();
             foreach ($flash as $mainflashkey => $mainflashval) {
                 $flashDetail->push(['campaign_id' => $mainflashval['campaign_id'], 'campaign_name' => $mainflashval['campaign_name'], 'username' => $mainflashval['username'], 'discount_type' => $mainflashval['discount_type'] == 1 ? 'Flatdiscount' : 'PercentageDiscount', 'discount_value' => $mainflashval['discount_value'], 'available_from' => date('d F Y - h:i A', $mainflashval['available_from']), 'available_upto' => date('d F Y - h:i A', $mainflashval['available_upto']), 'category' => $mainflashval['category'], 'campaign_status' => $mainflashval['campaign_status'], 'action' => '', 'supplierId' => Session::get('fs_supplier')['id']]);
             }
             //                echo'<pre>';print_r($flashDetail);die("xcfgb");
             return Datatables::of($flashDetail)->addColumn('action', function ($flashDetail) {
                 return '<span class="tooltips" title="Edit Flashsale Details." data-placement="top"> <a href="/supplier/edit-flashsale/' . $flashDetail['campaign_id'] . '" class="btn btn-sm grey-cascade" style="margin-left: 10%;">
                                                 <i class="fa fa-pencil-square-o"></i>
                                             </a>
                                         </span>
                                         <span class="tooltips" title="Delete Flashsale Details." data-placement="top"> <a href="#" data-cid="' . $flashDetail['campaign_id'] . '" class="btn btn-danger delete-flashsale" style="margin-left: 10%;">
                                                 <i class="fa fa-trash-o"></i>
                                             </a>
                                         </span>';
             })->addColumn('campaign_status', function ($flashDetail) {
                 $button = '<td style="text-align: center">';
                 $button .= '<button class="btn ' . ($flashDetail['campaign_status'] == 1 ? "btn-success" : "btn-danger") . ' flashsale-status" data-id="' . $flashDetail['campaign_id'] . '" data-set-by="' . $flashDetail['supplierId'] . '">' . ($flashDetail['campaign_status'] == 1 ? 'Active' : 'Inactive') . ' </button>';
                 $button .= '</td>';
                 return $button;
             })->removeColumn('for_shop_id')->removeColumn('for_product_ids')->removeColumn('for_product_ids')->removeColumn('campaign_banner')->make();
             break;
         case 'changeFlashsaleStatus':
             $campaignId = $inputData['campaignId'];
             $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$campaignId]];
             $dataToUpdate['campaign_status'] = $inputData['status'];
             $dataToUpdate['status_set_by'] = $inputData['userId'];
             $updateResult = $objCampaignModel->updateFlashsaleStatus($dataToUpdate, $where);
             if ($updateResult == 1) {
                 echo json_encode(['status' => 'success', 'msg' => 'Status has been changed.']);
             } else {
                 echo json_encode(['status' => 'error', 'msg' => 'Something went wrong, please reload the page and try again.']);
             }
             break;
         case 'deleteFlashsale':
             $campaignId = $inputData['campaignId'];
             $where = ['rawQuery' => 'campaign_id = ?', 'bindParams' => [$campaignId]];
             $deleteStatus = $objCampaignModel->deleteFlashsale($where);
             if ($deleteStatus) {
                 echo json_encode(['status' => 'success', 'msg' => 'User Deleted']);
             } else {
                 echo json_encode(['status' => 'error', 'msg' => 'Something went wrong, please reload the page and try again.']);
             }
             break;
         default:
             break;
     }
 }
Example #24
0
 /**
  * Create one or more new model records in the database
  *
  * @param array $data
  *
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function createMultiple(array $data)
 {
     $models = new Collection();
     foreach ($data as $d) {
         $models->push($this->create($d));
     }
     return $models;
 }
Example #25
0
 /**
  * @author EB, EA, WN
  * @param Merchant $merchant
  * @return Collection
  */
 protected function fetchMerchantLocations(Merchant $merchant)
 {
     $installations = $merchant->installations()->get();
     $merchantLocations = new Collection();
     foreach ($installations as $installation) {
         $installationLocations = $installation->locations()->get();
         foreach ($installationLocations as $location) {
             $merchantLocations->push($location);
         }
     }
     return $merchantLocations;
 }
Example #26
0
 public function getChartingImages($search_string = "")
 {
     $images = new Collection();
     $files = [];
     if ($search_string) {
         $files = File::where('patient_id', $this->id)->where(function ($query) use($search_string) {
             $query->where('name', 'LIKE', '%' . $search_string . '%')->orWhere('description', 'LIKE', '%' . $search_string . '%');
         })->get();
     } else {
         $files = $this->files;
     }
     foreach ($files as $f) {
         if ($f->icon->type == 'Image') {
             $images->push($f);
         }
     }
     return $images;
 }
Example #27
0
 public function showEmail($id)
 {
     $email = Email::findOrFail($id);
     $mailbox = Mailbox::findOrFail($email->mailbox_id);
     $email->markAsRead();
     if (!is_null(session('mailbox_view')) && session('mailbox_view') != 'inbox') {
         switch (session('mailbox_view')) {
             case 'favourites':
                 $emails = $mailbox->emails()->where('favourited', 1)->orderBy('created_at', 'desc')->get();
                 $mailbox_heading = "Favourites";
                 $mailbox_icon = "star";
                 $mailbox_icon_color = "#454545";
                 break;
             case 'patient':
                 $patient = Patient::findOrFail(session('mailbox_view_patient_id'));
                 $emails = $patient->emails;
                 $mailbox_heading = $patient->first_name . ' ' . $patient->last_name;
                 $mailbox_icon = "user";
                 $mailbox_icon_color = "#454545";
                 view()->share('show_patient_nav', true);
                 break;
             case 'tag':
                 $tag = EmailTag::findOrFail(session('mailbox_view_tag_id'));
                 $emails = $tag->emails;
                 $mailbox_heading = $tag->name;
                 $mailbox_icon = "tag";
                 $mailbox_icon_color = $tag->color_bg;
                 break;
             case 'unread':
                 $emails = $mailbox->emails()->where('read', 0)->orderBy('created_at', 'desc')->get();
                 $mailbox_heading = "Unread";
                 $mailbox_icon = "asterisk";
                 $mailbox_icon_color = "#454545";
                 break;
             default:
                 $emails = $mailbox->emails()->orderBy('created_at', 'desc')->get();
                 $final_emails = new Collection();
                 foreach ($emails as $tmp_email) {
                     if ($tmp_email->tags()->count() == 0) {
                         $final_emails->push($tmp_email);
                     }
                 }
                 $emails = $final_emails;
                 $mailbox_heading = "Inbox";
                 $mailbox_icon = "inbox";
                 $mailbox_icon_color = "#454545";
                 break;
         }
     } else {
         $emails = $mailbox->emails()->orderBy('created_at', 'desc')->get();
         $final_emails = new Collection();
         foreach ($emails as $tmp_email) {
             if ($tmp_email->tags()->count() == 0) {
                 $final_emails->push($tmp_email);
             }
         }
         $emails = $final_emails;
         $mailbox_heading = "Inbox";
         $mailbox_icon = "inbox";
         $mailbox_icon_color = "#454545";
     }
     $vars = ["mailbox_icon" => $mailbox_icon, "mailbox_icon_color" => $mailbox_icon_color, "mailbox_heading" => $mailbox_heading, "active_email" => $id, "mailbox" => $mailbox, "emails" => $emails, "email" => $email, "sidebar" => true];
     if (session('mailbox_view') == 'patient') {
         $vars['patient'] = $patient;
         $vars['current_nav'] = 9;
     }
     return view('backend.page.mailbox-inbox')->with($vars);
 }
 /**
  *
  * @param MessageIterator|Message[]
  *
  * @return Collection
  */
 public function getCollectionMessages($MessageIterator)
 {
     $messages = new Collection();
     foreach ($MessageIterator as $value) {
         $message = new \stdClass();
         $message->number = $value->getNumber();
         $message->subject = $value->getSubject();
         $message->from = $value->getFrom();
         $message->date = $this->formatdate($value->getDate());
         $message->seen = $value->isSeen();
         $messages->push($message);
     }
     return $messages->sortByDesc('number');
 }
 /**
  * Get all permissions as collection.
  *
  * @return \Illuminate\Database\Eloquent\Collection
  */
 public function getPermissions()
 {
     if (!$this->permissions) {
         $rolePermissions = $this->rolePermissions()->get();
         $userPermissions = $this->userPermissions()->get();
         $deniedPermissions = new Collection();
         foreach ($userPermissions as $key => $permission) {
             if (!$permission->pivot->granted && $rolePermissions->contains($permission)) {
                 $deniedPermissions->push($permission);
             }
         }
         $permissions = $rolePermissions->merge($userPermissions);
         $this->permissions = $permissions->filter(function ($permission) use($deniedPermissions) {
             return !$deniedPermissions->contains($permission);
         });
     }
     return $this->permissions;
 }
 /**
  * Create an array of new instances of the related model.
  *
  * @param  array  $records
  * @param  array   $properties The relationship properites
  * @return array
  */
 public function createMany(array $records, array $properties = array())
 {
     $instances = new Collection();
     foreach ($records as $record) {
         $instances->push($this->create($record, $properties));
     }
     return $instances;
 }