Laravel 5.7 fill data direct from database to select input - laravel-5

I want to get direct data in master table with format array($key => $value) :
in controller:
$result = array();
$color_list = Master::whereRaw("type = 'color'")->get();
// format data for select input
foreach ($color_list as $value) {
$result[$value->id] = $value->name;
}
return view('backend.product.create', compact('result')
in View:
{!! Form::select('color', $result) !!}
Purpose: Do not use foreach to build data for the selected input
i find a code:
$color_list = Master::lists('id', 'name');
but it not work on Laravel 5.7
Can anyone please help?

You can use this
$color_list = Master::whereRaw("type = 'color'")->pluck('name', 'id');
result must be
Collection {#499
#items: array:10 [
117 => 'master1'
118 => 'master2'
119 => 'master3'
.........
]
}
or for get array use
$color_list = Master::whereRaw("type = 'color'")->pluck('name', 'id')->all();
result must be array

$color_list = Master::whereRaw("type = 'color'")->pluck('name', 'id');
The pluck method retrieves all of the values for a given key
Doc Laravel

Related

INvalid argument foreach laravel when isnsert multiple rows

i want to update status receive to yes after that data also insert to other table multiple rows, i using ajax
this is my controller
public function bulkupdate(Request $request, ItemPR $item_code)
{
if($request->ajax())
{
$item_code = $request->item_code;
$item = ItemPR::whereIn('item_code', explode(",", $item_code))->update(['received'=> 'yes']);
$data = [];
foreach($item as $value){
$data[] = [
'item_code' => $value->item_code,
];
}}
WarehouseInventory::insert($data);
return response()->json(['success'=>"Products Updated successfully."]);
}
but i getting error like this
invalid argument for suplied foreach
how to fix that ?
plis help
thanks

Laravel : How can i get old and new value by updateOrCreate

I want update or create in data base
but i want get the old value and updated value because i want to compare between these two value
for example
this item in table user
name = Alex and Order = 10
so now i want update this person by
name = Alex and Order = 8
Now After updating or creating if not exist
just for update i want get
Old order 10 | And new Order 8
I want compare between these order
i have tryin getChange() and getOriginal() but two the function give me just the new value.
Please Help
You can get the old value using getOriginal if you have the object already loaded.
For example :
$user = User::find(1);
$user->first_name = 'newname';
// Dumps `oldname`
dd($user->getOriginal('first_name'));
$user->save();
However in case of updateOrCreate, you just have the data. I am not sure about a way to do it using updateOrCreate but you can do simply do :
$user = User::where('name', 'Alex')->first();
$newOrder = 10;
if($user){
$oldOrder = $user->getOriginal('order');
$user->order = $newOrder;
$user->save();
}
Is the name unique in the table? Because if it is not you will have updates on multiple rows with the same data.
So the best approach is to use the unique column which is probably the ID.
User::updateOrCreate(
[ 'id' => $request->get('id') ], // if the $id is null, it will create new row
[ 'name' => $request->get('name'), 'order' => $request->get('order') ]
);
Solution
$model = Trend::where('name', $trend->name)->first();
if ($model) {
$model->old_order = $model->getOriginal('order');
$model->order = $key + 1;
$model->save();
} else {
Trend::where('order', $key + 1)->delete();
$new = new Trend();
$new->name = $trend->name;
$new->old_order = $key + 1;
$new->order = $key + 1;
$new->tweet_volume = $trend->tweet_volume;
$new->save();
}

How to optimize code in Laravel?

I use the following code to get data from two related tables:
$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;
$subcategories = $objectModel::with("translate", "parent")->get();
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
array_unshift($arr, 'Select category');
return $arr;
In result this part of code I get array with key => value to insert this in select list in Blade template.
But I desire to escape a loop:
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
And get clear collection from request. How can I do it?
You can use Laravel Collections https://laravel.com/docs/5.3/collections
$arr = ProductCategory::with("translate", "parent")->get()
->mapWithKeys(function ($item, $key) {
return [$item->translate()->first()->objectId => $item->translate()->first()->name];
})
->all();

ChartJS and Laravel5

I have the following code in PHP controller:
public function getMainAdminBackend(){
$user_info = \DB::table('users')
->select('role_id', \DB::raw('count(*) as total'))
->groupBy('role_id')
->get();
return view('admin.main')->with('userInfo',$user_info);
}
In the view I have this chart.js:
<?php
$data = array(
'Jan' => array(33),
'Feb' => array(32),
'Mar' => array(12)
);
?>
{!! app()->chartbar->render("BarChart", $data) !!}
How can I convert the array of controller with the format required to JS Chart ?
EDIT
Now I receive the following format , the graphic show the number 1,2,3 but cant't print the lines of the graphics.
array(3) { [1]=> int(35) [2]=> int(20) [3]=> int(35) }
In your controller you call return view('admin.main')->with('userInfo',$user_info);
with('userInfo',$user_info) sets a $userInfo variable in your view with the content of $user_info, so just something like that should do the trick
{!! app()->chartbar->render("BarChart", $userInfo) !!}
EDIT: i assumed $user_info was already in the correct format but you couldn't figure out how to display it. Reading your comments i better understand your needs.
I don't know which data format chartJS and what you want to display. Looking $data example and your DB query, i assume you want to display data in the format "role_id" => count(*)
so, in that case, i would do something like
$userArray = array();
foreach($user_info as $row) {
$userArray[$row->role_id] = $row->total;
}
return view('admin.main')->with('userInfo',$userArray);
Looks like you need to put the data in the right format:
public function getMainAdminBackend() {
$user_info = \DB::table('users')
->select('role_id', \DB::raw('count(*) as total'))
->groupBy('role_id')
->get();
$data = [];
if ($user_info) {
foreach ($user_info as $month => $value) {
$data[date("M", mktime(0, 0, 0, $month, 1, 0))] = [$value];
}
}
return view('admin.main')->with('userInfo', $data);
}

Array from Controller to model [codeIgniter]

here's my problem:
Codeigniter's doc says this :
<?php
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
?>
I just want to pass conditions to my where clause from controller to model so :
Controller
<?php
$condition = array('id' => $id_user)
$data['info_user'] = $this->user_model->get_user($condition);
?>
Model
public function get_user($condition)
{
$q = $this
->db
->where($condition)
->get('users');
if($q->num_rows > 0)
{
return $q->row();
}
}
This return : SELECT * FROM (users) WHERE 3 IS NULL
But when I put my array directly in the model ($
There is no need to pass an array and I'm not even positive that it can be done the way you're trying to do it. Just pass the value itself to the model as below. Answer edited to show multiple variables.
Controller:
$data['info_user'] = $this->user_model->get_user($id_user,$user_login);
Model:
public function get_user($id_user,$user_login)
{
$q = $this
->db
->where('id_user',$id_user)
->or_where('user_login',$user_login);
->get('users');
if($q->num_rows == 1)
{
return $q->row();
}
}
As a side note when you want a single result from your database, as in retrieving a user ALWAYS check for a single result and not > 0. You want to ensure you're only getting one user back.

Resources