I am using Angular2 for my frontend and laravel for my back end and I'm having trouble saving the data to the database
Each of the keys in the Order[] (ex prodName, prodDesc) are the same as the column names in the database so I was trying to loop the request and save the data but its not working
public function Order(Request $request) {
$input = $request->all();
$order = new Order;
foreach ($input as $key => $value) {
if (array_key_exists($key, $input) && !empty($value)) {
$order->$key = $value;
}
}
}
if($order->save()) {
return response()->json(['order' => $order], 201);
}
order.interface.ts
export interface Order {
prodName: string;
prodDesc: string;
}
Adding the item to the order
addToOrder.component.ts
orders = [] as Order[];
saveItem(): void {
this.orders.push({prodName: this.prodName, prodDesc: this.prodDesc});
this.dataService.save(this.orders).then(() => {
this.navCtrl.pop(Search);
});
}
How each item is stored in storage
order.storage.ts
save(data : Order[]): Promise<any> {
return this.getData().then((products: any[]) => {
if (products) {
products = products.concat(data);
return this.storage.set('products', products);
}
return this.storage.set('products', data);
});
}
How I retrieve the order from storage
order.component.ts
private order = [] as Order[];
constructor(public dataService: OrderStorage, public OrderService: OrderService) {
this.dataService.getData().then((products) => {
if (products) {
this.order = products;
}
});
}
onSubmit() {
this.OrderService.submit(this.order)
.subscribe();
}
Posting the data to the back end
order.service.ts
submit(order: Order[]): Observable<any> {
return this.http.post(localapi.app, order)
.map(
(response: Response) => {});
}
Structure of the order data being sent
Retrieving the data on the backend
public function Order(Request $request) {
$input = $request->all();
var_dump($input);
}
the var_dump output
It's actually foreach ($input as $key => $arr), then you can use your loop:
foreach ($input as $arr) {
foreach ($arr as $key => $value) {
if (array_key_exists($key, $arr) && !empty($value)) {
$order->$key = $value;
}
}
}
The first set of elements you will encounter in your loop are arrays, then you can loop the property off of your array.
Related
Basically I want to sort them based on the highest - lowest avg rating but I can't do it since I've already fetched the data (paginate(12)).
Adding sortBy in the if else section is not possible since I do not have yet the avg_rating data. I tried it after foreach but keeps throwing error.
Any workarounds here so I can dynamically sort it out?
public function render()
{
$recipe_default = Recipe::where('is_approved', 1);
if(is_null($this->name_atoz))
{
$recipe_default = $recipe_default->orderBy('id', 'asc')->paginate(12);
}
elseif($this->name_atoz == true)
{
$recipe_default = $recipe_default->orderBy('recipe_name')->paginate(12);
}
elseif($this->name_atoz == false)
{
$recipe_default = $recipe_default->orderBy('recipe_name', 'desc')->paginate(12);
}
foreach($recipe_default as $key => $value)
{
$recipe_default[$key]->avg_rating = Feedback::where('recipe_id', $value->id)->avg('rating');
$recipe_default[$key]->feedback_count = Feedback::where('recipe_id', $value->id)->count();
$recipe_default[$key]->tag_name = Taggable::where('taggable_id', $value->id)->where('taggable_type', 'recipe')->value('tag_name');
}
return view('livewire.content-management', [
'recipes' => $recipe_default
]);
}
I need to print a main menu and instead of having a database where the links/ routes are stored I thought it there would be a way to get all routes that are in a named group, but all I find is getting routes by action.
web.php
Route::group(['as' => 'main'], function () {
Route::get('/', function () {
return view('pages.start');
})->name('Home');
Route::get('/foobar', function () {
return view('pages.foobar');
})->name('Home');
Route::get('/business', function () {
return view('pages.business');
})->name('Business');
});
I was looking for something like:
$routes = getRoutesByGroup('main');
I cannot really believe that a function like that doesnt exist in current Laravel but I cant seem to find this. What am I missing?
Maybe this can solve partially in your case
function getRoutesByStarting($start = '')
{
$list = \Route::getRoutes()->getRoutesByName();
if (empty($start)) {
return $list;
}
$routes = [];
foreach ($list as $name => $route) {
if (\Illuminate\Support\Str::startsWith($name, $start)) {
$routes[$name] = $route;
}
}
return $routes;
}
usage
getRoutesByStarting('main')
More general solution
function getRoutesByGroup(array $group = [])
{
$list = \Route::getRoutes()->getRoutes();
if (empty($group)) {
return $list;
}
$routes = [];
foreach ($list as $route) {
$action = $route->getAction();
foreach ($group as $key => $value) {
if (empty($action[$key])) {
continue;
}
$actionValues = Arr::wrap($action[$key]);
$values = Arr::wrap($value);
foreach ($values as $single) {
foreach ($actionValues as $actionValue) {
if (Str::is($single, $actionValue)) {
$routes[] = $route;
} elseif($actionValue == $single) {
$routes[] = $route;
}
}
}
}
}
return $routes;
}
usage
getRoutesByGroup(['middleware' => 'api']);
getRoutesByGroup(['middleware' => ['api']]);
getRoutesByGroup(['as' => 'api']);
getRoutesByGroup(['as' => 'api*']);
getRoutesByGroup(['as' => ['api*', 'main']]);
$allRoutes = Route::getRoutes()->getRoutes(); // fetch all rotues as array
$name = 'main'; // specify your full route name
$grouped_routes = array_filter($allRoutes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// output of route objects in the 'main' group
dd($grouped_routes);
I have a loop inside loop on Laravel collection, and sometimes i need to delete some objects from second loop collection. Here is the code
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
}
return $all_groups;
}
The problem is that collection of group->templates turns from simple(not assoc) array to object. Here is example how response looks
I am trying to flatten $group->templates->flatten() but in final response templates are still as object but not as array.
This test flatten works
...
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
return $group->templates->flatten()//This code works i get fluttened array
}
But final variant still returns me object instead of array
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->templates->forget($key);
}
}
$group->templates->flatten()//Use flatten here
}
return $all_groups;//Templates are returned not as an array but still as an object (Same variant as on attached image)
}
Use values() to reset the keys and setRelation() to replace the relationship:
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
foreach ($group->templates as $key => $template)
{
if($template->id = $id)
{
$group->setRelation('templates', $group->templates->forget($key)->values());
}
}
}
return $all_groups;
}
You can also use except() instead of forget():
public function remove_if_found($id)
{
$all_groups = Group::all();
$all_groups->load('templates');
foreach ($all_groups as $group)
{
$group->setRelation('templates', $group->templates->except($id));
}
return $all_groups;
}
what i did is:
$input = $request->all();
//convert the post camelcase to snakecase
foreach ($input as $key => $val) {
$newKey = snake_case($key);
$input[$newKey] = $val;
if ($newKey != $key) {
unset($input[$key]);
}
}
after integrating data,use helper function to convert snakecase to camelcase again by the following function:
function convert_snakeCase_to_CamelCase($data)
{
if ($data) {
foreach ($data as $key1 => $val1) {
$newKey1 = camel_case($key1);
if ($newKey1 != $key1) {
unset($data[$key1]);
}
$data[$newKey1] = $val1;
if (is_array($val1) && !empty($val1)) {
foreach ($val1 as $key2 => $val2) {
$newKey2 = camel_case($key2);
if ($newKey2 != $key2) {
unset($data[$newKey1][$key2]);
}
$data[$newKey1][$newKey2] = $val2;
if (is_array($val2) && !empty($val2)) {
foreach ($val2 as $key3 => $val3) {
$newKey3 = camel_case($key3);
if ($newKey3 != $key3) {
unset($data[$newKey1][$newKey2][$key3]);
}
$data[$newKey1][$newKey2][$newKey3] = $val3;
if (is_array($val3) && !empty($val3)) {
foreach ($val3 as $key4 => $val4) {
$newKey4 = camel_case($key4);
if ($newKey4 != $key4) {
unset($data[$newKey1][$newKey2][$newKey3][$key4]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4] = $val4;
if (is_array($val4) && !empty($val4)) {
foreach ($val4 as $key5 => $val5) {
$newKey5 = camel_case($key5);
if ($newKey5 != $key5) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$key5]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5] = $val5;
if (is_array($val5) && !empty($val5)) {
foreach ($val5 as $key6 => $val6) {
$newKey6 = camel_case($key6);
if ($newKey6 != $key6) {
unset($data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$key6]);
}
$data[$newKey1][$newKey2][$newKey3][$newKey4][$newKey5][$newKey6] = $val6;
}
}
}
}
}
}
}
}
}
}
}
}
return $data;
}
its working absolutely fine.I was wondering is there any solution better plugins for angular or laravel to convert the post data and send response data in required case?
On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}