How to create query for google bar chart in laravel? - laravel

This is bar graph i want to draw and i am struck in queries
My Database look like where i want to show population of country of 2020 Year
id | country_name | population | created_at
1 | USA | 2000000000 | 2020-02-04
2 | China | 2200000000 | 2020-02-04
3 | Russia | 12000000 | 2020-04-02
My Query look like this. I am just trying to build query but not getting result.Maybe there are some mistake.At first i making $countries variable to get all countries.
public function barChart(){
$countries=Country::get();
$graphic_header=['Year'];
$countrydata=[];
$actionDate=[];
$country_name=[];
foreach ($countries as $country) {
array_push($country_name, $country->name);
array_push($actionDate, date('Y', strtotime($country->created_at)));
$actionDate = array_unique($actionDate);
}
$graphic_header=array_merge($graphic_header,$country_name); //Dynamic Header
array_push($countrydata,$graphic_header);
foreach($actionDate as $d) {
$d = [$d];
$d = array_pad($d, sizeof($graphic_header), 0);
array_push($data, $d);
}
foreach ($countries as $country){
$date = date('Y', strtotime($country->created_at));
foreach ($data as $in =>$gd){
if ($date == $gd[0]) {
$index = (array_search($country->country_name, $graphic_header));
$country_data[$in][$index] = $country->population;
}
}
}
return response()->json([
'data'=> $country_data,
]);
}

simply use this groupBy collection method
$countries=Country::get();
$countries = $countries->groupBy('country_name');
$countries->toArray();

Related

How to send notices to members who have different membership roles?

Immediately, I want to ask as I asked in the title.
I Have controller like this:
public function store(Request $request)
{
//
$this->validate($request, [
'status'=> 'required|min:1|max:2',
'subject' => 'required|min:10|max:255',
'body' => 'required|min:10|max:100000'
]);
if ($request->status == 1){
$this->validate($request, [
'email' => 'required|email',
]);
$user = User::whereEmail($request->email)->firstOrFail();
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$notice->file = 'uploads/posts/'. $featured_new_name;
}
$notice->save();
session()->flash('message', "Send Message to ".$user->name." Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
else {
$users = User::all();
if ($request->hasFile('featured')){
$featured = $request->featured;
$featured_new_name = time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$attachment = 'uploads/posts/'. $featured_new_name;
}
foreach ($users as $user){
$notice = new Notice();
$notice->user_id = $user->id;
$notice->title = $request->subject;
$notice->priority = $request->priority;
$notice->body = $request->body;
$notice->status = 0;
if ($request->hasFile('featured')){
$notice->file = $attachment;
}
$notice->save();
}
session()->flash('message', "Send Message to all Users Successful!");
Session::flash('type', 'success');
Session::flash('title', 'Message Send Success!');
return redirect()->route('adminMessage.create');
}
}
I Have 2 status in this field:
For Status 1, I send for selected member (Only One)
For Status 2, I send for all User use $user= User::all();
So I need for help with Send Notice with Membership_role
I Have Memberships Tables, for example like this:
=========================
| id | name | count |
-------------------------
| 1 | free | 200 |
| 2 | free | 200 |
| 3 | free | 200 |
| 4 | free | 200 |
How do I send a message to Membership Id: 2,3,4
If it is a property at the User model, you can use querys to find the user or users you want.
/*
I use a switch just in case you have more than 2 notice statuses to handle
the sendTo functions are functions declared in your controller to handle the cases.
*/
switch($notice->status){
/*Query the user by the membership id to send the notice*/
case 1:
$user = User::where('membership_id',$the_membership)->first();
return $this->sendTo($user);
case 2:
/*Get all users*/
$users = User::all();
return $this->sendTo($users);
/*Handle other notice statuses*/
default:
return $this->sendToDefault();
}

Laravel : how to use pivot table for taggable system

I want create tag for posts
for example I created three new tags but submit a only a row in TaggablesTable
Tags Table:
id | name |
--------------
1 | first|
2 | two |
3 | three|
taggables Table:
tag_id|taggable_id|taggable_type
-------------------------------
3 | 1 |post
public function store(Request $request)
{
$data = $request->all();
$post = Post::create($data);
if ($post && $post instanceof Post) {
$tags = $request->input('tags');
foreach ($tags as $tag){
$newTag =Tag::firstOrCreate(['name'=>$tag]);
$tags= $newTag->id;
}
$post->tags()->sync($tags);
return redirect()->back();
}
}
How can it be done?
You are overwriting tags every time the loop runs. Map seems like an easier approach to your problem.
$data = $request->all();
$post = Post::create($data);
$tags = collect($request->input('tags'))->map(function (string $tag) {
return Tag::firstOrCreate(['name'=>$tag])->id;
})->all();
$post->tags()->sync($tags);
return redirect()->back();

Powershell fastest way to merge two arrays using a common property?

What's the fastest way to merge two arrays using a common property?
Users | Select *
Username : Joe.Doe
Office : Chicago
Email :
Username : Mike.Smith
Office : New York
Email :
...
UserEmails | Select *
AccountEmail : Mike.Smith
EmailAddress : mike-smith#example.com
AccountEmail : Joe.Doe
EmailAddress : jsmith12#example.com
...
The merge should result in:
UsersCompleteList | Select *
Username : Joe.Doe
Office : Chicago
Email : jsmith12#example.com
Username : Mike.Smith
Office : New York
Email : mike-smith#example.com
...
Something like for each ($user in $users) { ($user.Email = $userEmails | ? { $_.AccountEmail -eq $user.Username}).EmailAddress takes ages on large datasets.
Loop through one collection and store the values in a hash. Then loop through the other collection and pull the value back out of the hash. Something like:
$hash = #{}
$userEmails | %{ $hash[$_.AccountEmail] = $_.EmailAddress }
$users | %{ $_.Email = $hash[$_.Username] }
If you have other properties you can just store the original object:
$hash = #{}
$userEmails | %{ $hash[$_.AccountEmail] = $_ }
$users | %{
$item = $hash[$_.Username]
$_.Email = $item.EmailAddress
$_.Other = $item.SomethingElse
}
Or with loops instead of ForEach-Object including:
$hash = #{}
foreach($e in $userEmails) {
$hash[$e.AccountEmail] = $e
}
foreach($u in $users) {
$item = $hash[$u.UserName]
if ($item -ne $null) {
$u.Email = $item.EmailAddress
}
}

Laravel 5.5 recursive function to create menu

I have created a mysql table as below:
id | menuname | parentid
---+-------------------+---------
1 | dashboard | 0
2 | Content | 0
3 | Home Page Content | 2
4 | Banners | 2
5 | Settings | 0
6 | Block Content | 3
7 | Site Content | 3
So that the menu structure will look like:
dashboard
Content
Home Page Content
Block Content
Site Content
Banners
Settings
I have the controller:
public function index() {
$data = array();
$permissionRecord = Permission::all();
$this->categoryTree($permissionRecord);
dd('-end-);
$data['permissionRecord'] = $permissionRecord;
return view('Administrator.permission.permissionAdd',$data);
}
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
But this show the data :
Dashboard---Dashboard------Dashboard---------Dashboard------------Dashboard---------------Dashboard------------------Dashboard---------------------Dashboard------------------------Dashboard---------------------------Dashboard------------------------------Dashboard---------------------------------Dashboard------------------------------------Dashboard
Please note, I dd() inside the controller and did not passed the data to the view.
You've not accounted for the parent ID:
function categoryTree($permissionRecord, $parent_id = 0, $sub_mark = '')
{
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
echo $sub_mark.$row->name;
$this->categoryTree($permissionRecord, $row->id, $sub_mark.'---');
}
}
}
Try that and see what happens - Note I've wrapped the recursive function call in an if() that checks if the current records parentId is equal to the parent ID passed into the method.
To get it to display the items in an indented list:
public function categoryTree($permissionRecord, $parent_id = 0)
{
$html = '<ul>';
foreach($permissionRecord as $row) {
if ($row->parentid == $parent_id) {
$html .= '<li>' . $row->menuname;
$html .= $this->categoryTree($permissionRecord, $row->id, $html);
$html .= '</li>';
}
}
$html .= '</ul>';
return $html;
}
Then just call:
$html = $this->categoryTree($permissionRecord);
Example of it working with a unit test

How to make dynamic drop down in php?

I want to make a dynamic drop down in CI.I had done it in CI by directly passing the values from model With its design by concatenation the html.. But now i want it without the html i.e. the function just only should return the array ...
my before function was something like this...
function category() {
$sql = $this->db->query("select * from ss_category where parent_id='0'");
$result = $sql->result();
//print_r($result);die();
$output = array();
foreach ($result as $ra) {
$output=$this->get_child($ra->cat_id);
}
//print_r($output);die();
return $output;
}
function get_child($parent_id) {
//echo "select * from ss_category where parent_id=" . $parent_id;
$sql = $this->db->query("select * from ss_category where parent_id=" . $parent_id);
$r = $sql->result();
if (!empty($r)) {
foreach ($r as $s) {
$this->get_child($s->cat_id);
}
//print_r($child);
}
//print_r($r);
}
I want to make drop down something like this..
-parent 1
-child 1
-subchild 1
-child 2
-child 3
-subchild 1
-parent 2
-child 1
My table structure is like this..
+---------------------------------------------------------------+
| cat_id category_name cat_slug parent_id level description |
+---------------------------------------------------------------+
| 1 Elecotronics Electronics 1 description |
+---------------------------------------------------------------+
function parent_sort($categories)
{
foreach($categories as $item)
$childs[$item->parent_id][] = $item;
foreach($categories as $item)
if (isset($childs[$item->category_id]))
$item->childs = $childs[$item->category_id];
return $childs[0];
}

Resources