I want to minimize this by removing if else statement using simple code in laravel 5.5 can someone help me with it?
public function shirts($type='')
{
if($type == 'glass') {
$shirt = Product::where('category_id','1')->get();
$products = Category::find(1);
} elseif ($type == 'ic') {
$shirt = Product::where('category_id','2')->get();
$products = Category::find(2);
} elseif ($type == 'cover') {
$shirt = Product::where('category_id','3')->get();
$products = Category::findOrFail(3);
} else {
$shirt = Product::all();
}
return view('front.shirt',compact('products','shirt'));
}
One way would be to create a mappings for your type and comparing the type with the mappings.
public function shirts($type = '')
{
$type_mappings = [
'glass' => 1,
'ic' => 2,
'cover' => 3
];
if(array_key_exists($type, $type_mappings)) {
$shirt = Product::where('category_id', $type_mappings[$type])->get();
$products = Category::find($type_mappings[$type]);
} else {
$shirt = Product::all();
$products = null;
}
return view('front.shirt', compact('products', 'shirt'));
}
Edit : i assumed you want to avoid if else not as what the title of question says if still i am unclear please add comment so i can update the answer Thanks!
Lets handle it somewhere else as i guess your function only has the responsibility to find product based on id it get not mapping part so we can have something like :
// Your function with single responsibility to return product.
public function shirts($category = '')
{
$type = $this->CategoryIdMapper($category);
if($type == 0) {
$shirt = Product::all();
$products = null;
} else{
$shirt = Product::where('category_id',$type_id)->get();
$products = Category::findOrFail($type_id);
}
return view('front.shirt',compact('products','shirt'));
}
//let the mapping part be done by some independent function which you can later modify accordingly and independently.
public function CategoryIdMapper($category)
{
$categories = ['glass'=>1, 'ic'=> 2, 'cover' => 3 ];
if(array_key_exist($category,$categories))
{
return $categories[$category];
}
return 0;
}
Related
I'm trying to create a function that will replicate/clone/duplicate a product including all it's properties and it's shipping options.
However, I succeeded to duplicate the product but the shipping options are not replicated. See my codes below;
Any help will be highly appreciated
Thanks
public function CreateProductPost(Request $request){
if (Auth::user()->vendor == false) {
return redirect()->route('profile');
}
if ($request->name == null) {
session()->flash('errormessage','Product name is required');
return redirect()->back()->withInput();
}
if (mb_strlen($request->name) > 60) {
session()->flash('errormessage','Product name cannot be longer than 60 characters.');
return redirect()->back()->withInput();
}
if ($request->category_id == null) {
session()->flash('errormessage','Product category is required');
$shippingoptions[] = $opt;
}
}
$product = new Product;
$product->name = $request->name;
$product->uniqueid = random_int(10000, 99999);
$product->category_id = $category->id;
$product->description = $request->description;
$product->refund_policy = $request->refund_policy;
$product->fromc = $request->fromc;
$product->tocount = $request->tocount;
$product->price = $request->price;
$product->currency = $request->currency;
$product->inventory = $request->inventory;
if ($request->image !== null) {
$product->image = $request->image->store('uploads','public');
}
$product->buyout = 0;
$product->fe = $fe;
$product->seller_id = Auth::user()->id;
$product->save();
foreach ($shippingoptions as $opt) {
$so = new ShippingOption();
$so->product_id = $product->id;
$so->desc = $opt['desc'];
$so->days = $opt['days'];
$so->price = $opt['price'];
$so->save();
}
session()->flash('successmessage','Product successfully created');
return redirect()->route('products');
}
function DuplicateProductPost($uniqueid, Request $request){
$product = Product::where('uniqueid',$uniqueid)->first();
if ($product == null) {
return redirect()->route('products');
}
if (Auth::user()->id !== $product->seller->id) {
return redirect()->route('products');
}
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
session()->flash('successmessage','Product successfully duplicated');
return redirect()->route('products');
}
Any help will be highly appreciated
Thanks
You need to replicate both your Product and ShippingOption models, so use the following logic:
$product = Product::where('uniqueid',$uniqueid)->first();
...
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
foreach($product->shippingOptions AS $shippingOption){
$newShippingOption = $shippingOption->replicate();
$newShippingOption->product_id = $newProduct->id;
$newShippingOption->save();
}
Note, you need to have a relationship between Product and ShippingOption, otherwise you will need to manually query for them:
$oldShippingOptions = ShippingOption::where("product_id", "=", $product->id)->get();
foreach($oldShippingOptions AS $shippingOption){
...
}
The ->replicate() method does not clone all related records, as that might not be the intended requirement, so you need to do it manually.
Hello I am writing an php application and currently I'm stuck at a method that retrives flights from the database and applies diffrent filters to it. There are no problems when I initially load the page without any filters applied, all records from DB are loaded as expected. Then again everything as expected when I use "Departure Airport" or "Arrival Airport" filters along with "Bookable Only" filter.
It is whole of another story when you try to use "Bookable Only" filter on its own, it doesn't load any records from database. That's the same with "Aircraft" filter, doesn't work on its own and with "Bookable Only" filter but works when combined with both or either one of Airport filters + "Bookable Only" filter
Schedules_model.php
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
if($available === TRUE) {
echo 'work';
foreach($schedules as $key => $schedule) {
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
break;
}
} else {
$schedulesAvailable[$key] = $schedule;
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
schedules.php
public function search()
{
$this->data['pageTitle'] = 'Schedule Search';
$this->data['pageDisplayedTitle'] = 'Schedule Search';
$available = (bool) $this->input->post('available');
$this->data['schedules'] = $this->Schedules->getFilteredSchedule($available, $this->input->post('departureICAO'), $this->input->post('arrivalICAO'), $this->input->post('aircraftId'));
$airportsList = $this->Airports->getAllAirports(TRUE, TRUE); // Get set of all active airports
$aircraftsList = $this->Aircrafts->getAllAircrafts(TRUE, TRUE); // Get set of all active airports
// Prepare form inputs
$this->data['departureICAO'] = array(
'name' => 'departureICAO',
'id' => 'departureICAO',
'selected' => $this->input->post('departureICAO'),
'options' => $airportsList,
);
$this->data['arrivalICAO'] = array(
'name' => 'arrivalICAO',
'id' => 'arrivalICAO',
'selected' => $this->input->post('arrivalICAO'),
'options' => $airportsList,
);
$this->data['aircraftId'] = array(
'name' => 'aircraftId',
'id' => 'aircraftId',
'selected' => $this->input->post('aircraftId'),
'options' => $aircraftsList,
);
$this->data['available'] = array(
'name' => 'available',
'id' => 'available',
'checked' => set_checkbox('available', $this->input->post('available'), FALSE),
'value' => TRUE,
);
$this->load->view('schedules/scheduleSearch', $this->data);
}
I tried debugging everything and following the process step by step as well as trial and error method but none give expected effects. Any ideas?
By trial and error method I have found some kind of a work around that some how does the job. If anyone has any suggestions regarding it or how I could improve it, please feel free, as I am looking for performance in the app.
The required changes were in the Model:
public function getFilteredSchedule($available, $departureICAO, $arrivalICAO, $specificAircraftId)
{
$this->db->select('*');
if($departureICAO != FALSE) {
$this->db->where('departureICAO', $departureICAO);
}
if($arrivalICAO != FALSE) {
$this->db->where('arrivalICAO', $arrivalICAO);
}
if($specificAircraftId != FALSE) {
$this->db->where('aircraftId', $specificAircraftId);
}
$schedules = $this->db->where('active', 1)
->order_by('id', 'asc')
->get('schedules')
->result_array();
$schedulesAvailable = array();
// Check if any of the filters is required
if(!$this->RebuildVA->mustBeAtDepartureAirport() && $this->RebuildVA->allowMultipleAircraftBookings() && $this->RebuildVA->allowMultiplePilotBookings()) {
$schedulesAvailable = $schedules;
// Check if only bookable flights has been checked
} elseif($available === TRUE) {
foreach($schedules as $key => $schedule) {
// Allow multiple schedule bookings
// Check if the aircraft must be at departure airport
if($this->RebuildVA->mustBeAtDepartureAirport()) {
if($this->Aircrafts->isAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
// Check if use of other aircraft of same type is allowed
if($this->RebuildVA->allowOtherAircraftUse()) {
if($this->Aircrafts->aircraftTypeAtAirport($schedule['aircraftId'], $schedule['departureICAO'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
unset($schedulesAvailable[$key]);
continue;
}
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per aircraft
if(!$this->RebuildVA->allowMultipleAircraftBookings()) {
if(!$this->Aircrafts->isBooked($schedule['aircraftId'])) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
// Check if there is a limit of only one booking at time per pilot
if(!$this->RebuildVA->allowMultiplePilotBookings()) {
if(!$this->Pilots->hasBookedFlight($this->session->userdata('pilotId'))) {
$schedulesAvailable[$key] = $schedule;
} else {
unset($schedulesAvailable[$key]);
continue;
}
} else {
if(isset($schedulesAvailable[$key])) {
$schedulesAvailable[$key] = $schedule;
}
}
}
} else {
$schedulesAvailable = $schedules;
}
return $schedulesAvailable;
}
I am trying to create an API using CakePHP that allows searching. For example:
http://localhost:8765/users/index/?username=admin
Which should return users with usernames equal to 'admin':
users: [
{
id: 3,
username: "admin",
image: "",
firstName: "Jeremy",
lastName: "Quick",
userTypeId: 1,
email: "jrquick#test.com",
groupId: 2
}
]
So far, I have been able to accomplish this with a custom get() in the AppController which checks the $_GET and $_POST array for fields on the model. But the function is getting more and more complicated and verging on hackiness as I add more functionality (range search, collection search, and child table filtering). Is there a better, more CakePHP friendly way of accomplishing this? Whether through pure cakephp or a plugin?
I think you want to use the Cakephp Search plugin. It has good documentation and uses a PRG method similar to what you are currently using. It will function just fine through an API. Here's a link to that plugin: github.com/FriendsOfCake/search
If You want to create API, You should create a MiddleWare at first, which will filter tokens, keys etc. to make Your API more protected.
Also, You should use Plugins and RESTful Routes, which will be very helpful.
To create plugin:
bin/cake bake plugin Api
Create Model:
bin/cake bake model Users
For example, You want to have UsersController in Api plugin:
<?php
namespace Api\Controller;
/* This controller will be extending like parent */
use Api\Controller\AppController;
use Api\Model\Table\UsersTable;
/**
* Class UsersController
* #package Api\Controller
* #property UsersTable $Users
*
*/
class UsersController extends AppController{
public function initialize(){
parent::initialize();
$this->loadModel('Api.Users');
}
public function getUser($field ='username', $username = false){
return $this->_jsonResponse(
[
'users' => $this->Users->findBy{ucfirst($field)}($username)
];
)
}
public function _jsonResponse($data, $code = 200){
$this->response->type('json');
$this->response->statusCode($code);
$this->response->body(
json_encode((array)$data)
);
return $this->response;
}
}
Route will be descripbed in plugins/config/routes.php. You need to create Route Map for API in /api path:
function (RouteBuilder $routes) {
$routes->resources('Users', [
'map' => [
'get-user' => [
'action' => 'getUser',
'method' => 'GET' /* Can be also as array ['GET', 'PUT', 'DELETE'] */
]
]
]);
$routes->fallbacks('DashedRoute');
}
If You have frequent calls, You should use Cache that calls and save them for some amount of time. For example - 10 minutes. Cache can be configured in config/app.php. You should create separate Cache prefix and use it in this way:
<?php
use Cake\Cache\Cache;
$data = [];
Cache::write('some_key', $data, 'prefix')
dump(Cache::read('some_key', 'prefix'));
It's just examples. If You will face some problems - just tell in comments :)
Also, use Migrations and Seeds instead dumping sql files
If You want to filter data from Middleware - You should have Event as argument, that will contain request data ($_POST) and request query($_GET) variables that You will be able to easily handle with.
From controllers You need to use $this->request->data to get POST data array or $this->request->query to get GET data array.
I haven't found an answer that seems to work exactly how I am wanting, so here is my current get command. It does allow searching by fields, join tables, greater/less than, in array, and like.
If anyone has recommendations to improve I will update my answer.
public function get() {
$response = new Response();
$model = $this->loadModel();
$fields = $this->getFields();
$joins = $this->getJoins();
$order = $this->getOrder();
$params = $this->getParams();
$limit = $this->getLimit();
$offset = $this->getOffset();
$query = $model->find('all', ['fields' => $fields]);
if (!is_null($joins)) {
$query->contain($joins);
}
if (sizeof($params['equals']) > 0) {
foreach ($params['equals'] as $equalsKey=>$equalsValue) {
$query->andWhere([$equalsKey => $equalsValue]);
}
}
if (sizeof($params['or']) > 0) {
foreach ($params['or'] as $orKey=>$orValue) {
$query->orWhere([$orKey => $orValue]);
}
}
if (!is_null($order)) {
$query->order([$order]);
}
if (!is_null($limit)) {
$query->limit($limit);
if (!is_null($offset)) {
$query->offset($offset);
}
}
$response->addMessage($model->table(), $query->toArray());
$response->respond($this);
}
private function getFields() {
$fields = [];
if (array_key_exists('fields', $_GET)) {
$fields = explode(',', $_GET['fields']);
}
return $fields;
}
private function getLimit() {
$limit = null;
if (array_key_exists('limit', $_GET)) {
$limit = $_GET['limit'];
}
return $limit;
}
private function getJoins() {
$joins = null;
if (array_key_exists('joins', $_GET)) {
$joins = explode(',', $_GET['joins']);
}
return $joins;
}
private function getOffset() {
$offset = null;
if (array_key_exists('offset', $_GET)) {
$offset = $_GET['limit'];
}
return $offset;
}
private function getOrder() {
$results = [];
if (array_key_exists('order', $_GET)) {
$orders = explode(',', $_GET['order']);
foreach ($orders as $order) {
$sign = substr($order, 0, 1);
$direction = 'ASC';
if (in_array($sign, ['+', '-'])) {
if ($sign === '-') {
$direction = 'DESC';
}
$order = substr($order, 1);
}
$result = $order;
if (strpos($result, '.') === false) {
$result = $this->loadModel()->alias() . '.' . $order;
}
$result = $result . ' ' . $direction;
$results[] = $result;
}
}
return (sizeof($results) == 0) ? null : implode(',', $results);
}
private function getParams() {
$params = [
'equals' => [],
'or' => []
];
$parentModel = $this->loadModel();
$array = array_merge($_GET, $_POST);
foreach ($array as $field=>$value) {
$comparisonType = 'equals';
$operator = substr($field, strlen($field) - 1);
if (in_array($operator, ['!', '>', '<'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator .= '=';
} else if (in_array($operator, ['|'])) {
$field = substr($field, 0, strlen($field) - 1);
$comparisonType = 'or';
$operator = '=';
} else if (in_array($operator, ['%'])) {
$field = substr($field, 0, strlen($field) - 1);
$operator = 'LIKE';
$value = '%'.$value.'%';
} else {
$operator = '=';
}
if ($value == 'null') {
$operator = (strpos($operator, '!') === false) ? 'IS' : 'IS NOT';
$value = null;
}
$field = str_replace('_', '.', $field);
if (strpos($field, '.') === false) {
$alias = $parentModel->alias();
} else {
$fieldExplosion = explode('.', $field);
$alias = $fieldExplosion[0];
$field = $fieldExplosion[1];
}
$model = null;
if ($parentModel->alias() !== $alias) {
$association = $parentModel->associations()->get($alias);
if (!is_null($association)) {
$model = $this->loadModel($association->className());
}
} else {
$model = $parentModel;
}
if (!is_null($model)) {
if ($model->hasField(rtrim($field, 's')) && !$model->hasField($field)) {
$field = rtrim($field, 's');
$value = '(' . $value . ')';
$operator = ' IN';
}
if ($model->hasField($field)) {
$params[$comparisonType][$alias.'.'.$field . ' ' . $operator] = $value;
}
}
}
return $params;
}
I have some sample code within a controller method that looks up a cookie and manipulates the model if it exists, or creates a new model and returns a new cookie if it doesn't.
Is it possible to add the cookie before I return the view such that the duplicated code can be written only once?
I'm just looking for efficiency and tidiness.
$cat = Cat::find($request->cookie('cat_id'));
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/');
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/')->withCookie(cookie('cat_id', $cat->id,10000));
}
The redirect() method returns a Illuminate\Http\RedirectResponse when a string is passed to it, which the Laravel routing stack interprets as a direction to send out a particular response header. So instead of returning twice, you can just do this:
$cat = Cat::find($request->cookie('cat_id'));
$redirect = redirect('/');
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
$redirect->withCookie(cookie('cat_id', $cat->id,10000));
}
return $redirect;
I am new in codeigniter and php.
I want to count post view number and store it database.
That means, I want to create a popular post plugin by counting post view.
But i can't do this.
Please anyone help me. Tell the way.
Here is my article Controller..
public function __construct(){
parent::__construct();
$this->load->model('article_m');
}
public function index($category_slug, $id, $slug=NULL){
// Fetch the article
$this->db->where('pubdate <=', date('Y-m-d'));
$this->data['article'] = $this->article_m->get($id);
$this->data['articles'] = $this->article_m->get();
// Return 404 if not found
count($this->data['article']) || show_404(uri_string());
if ($this->uri->segment(1) !== $this->data['cat']->category_slug) {
echo "Hi There, This is wrong";
}
$this->load->view('templates/article', $this->data);
}
}
Here is my Models:
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
Sorry for my bad english..
$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
star complex to do?
//function single post, query get by slug and id post
if(!isset($_SESSION['views'. $id]) || (isset($_SESSION['views'. $id]) && $_SESSION['views'. $id] != $id)){
$this->post_m->viewer($id); //load model viewer
$this->session->set_userdata('views'. $id, $id);
}
// Model "post_m"
function viewer($id)
{
$this->db->where('id', $id);
$this->db->set('views', 'views+1', FALSE);
$this->db->update('posts'); //table update
}
$id is id post