laravel orm: different result from almost same query - php

I've a very big doubt about how works laravel for a very simple thing:
If I call:
$companies=User::All();
Then I can use statement like this in a forach:
foreach($companies as $company)
$company['new_field']= 'something';
If i'm limiting the output of the query like:
$companies = DB::table('companies')
->select('id','name','email','business_name',...)->get();
The things doesnt work as before,
I try with or without the ->get()
I try to convert with ->toArray() (errors rised)
I try with put() and push() for collections method and agains errors...
How can I add a field in every item of the collection just to pass it to a view?

Try like this, hope it works for you:
$users=User::select('id','name','email','business_name',...)->get()->toArray();
and then use foreach loop like this:
foreach($users as $key => $value ){
$users[$key]['newField'] = "Demo";
}

If you are using Laravel and model in it so there is a better way to add custom attribute or field here is what i do for custom field
For Example :
There is a Model Name User
so in User Model
add a property name appends like :
class User extends Model
{
protected $appends = ['new_field'];
public function getNewFieldAttribute() // defining field logic here
{
return // your code
}
So you no need to use foreach and looping and adding new field
for more have a look on laravel doc : https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators
Suggestion
you can limit your output with Model too.
User::select('id','name','email','business_name',...)->get();
if you are making an array like
User::select('id','name','email','business_name',...)->get()->toArray();
so this will also give you your custom field

Related

Symfony relationship get by id in Entity without repository

I have in my Item ORM entity a relationship with Packs.
Now in my code I have a PackId and I have an Item. Now here's what I am trying in my code:
$item->getPackById($pack->getId);
In my Item Entity I try something like this:
public function getPackById(UuidInterface $packId)
{
return $this->packs[$packId];
}
I am not sure If I can do this without a repository or is there a better way?
Normally we try to avoid to much work in an entity but as you are certain that the packs UUID are unique you could try something with an array filter like :
public function getPackById(Uuid $uuid): ?Pack
{
$matching = array_filter((array)$this->packs, fn(Pack $pack) => $pack->getUuid() === $uuid);
return $matching[0];
}

Defining an array inside a class in php/laravel

I have a class called shoppingCart and i would like to define an array inside of it. But it seems i need to manually create an instance of an array to use it. I am sure there is a way but i can`t find it
My shopping chart class
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Product;
class shoppingChart extends Model
{
var $products = Array();
var $productCount=0;
public function ItemCount(){
return count($products);
}
}
When i try to use i get a null pointer exceptionn and whenn i checked it $products doesn`t seem to be in variable list.
array_push($sc->products, "test");
I can do it as below. When i am using the array. Works fine.
public function addToBasket(Request $request)
{
$product = new Product();
$product->id = Input::get('product_id');
if($request->session()->has('shoppingCart')){
$sc = $request->session()->get('shoppingCart');
$sc->products = Array(); // If i remove this line code doesn`t work
array_push($sc->products,$product);
$sc->productCount=$sc->itemCount();
}
}
Should i initiate the array everytime i use it ? Doesn`t make any sense to me..
Without knowing more about the architecture of your application i can't go into specifics but I have a feeling that you might not even need this array.
If you are looking at a ShoppingCart has many Product's, then try using an eloquent "Many to Many" relationship using relationships \Illuminate\Database\Eloquent\Relations\HasMany.
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
By having this relationship you will be able to get all products related to you cart by going $cart->products which will return an eloquent Collection of the products associated with the cart.

Calling function with return value in cakephp

I am new to cakephp. I have a problem with calling the function. here is my issue.
In Contrloller file i get all the values using the following function
public function index()
{
$conditions = array(
'order' => array('Histroy.chat_sk DESC')
);
$this->set('histroys', $this->Histroy->find('all',$conditions));
}
In My model file have the following,
class Histroy extends AppModel
{
public $tablePrefix = 'plc_';
public $useTable = 'chat_history';
}
In my view file i have listed the values using foreach() function and that as follows
foreach ($histroys as $histroy):
$oper_name = $histroy['Histroy']['operator_fk'];
$operator_email = $histroy['Histroy']['email'];
endforeach
in that opertaor_fk is a field in history table. So i need get the operator name by another table as operators. So i need to call that function in the view.
Ex : In core we can do like as,
$operator_name = operator_name($fetch['operator_id']);
Function should be like this:
function operator_name($id)
{
// Select the value for the matched field in the operator
return $operator_name;
}
In cakephp how can i retrieve the values.
Please help me out to fix this. Thanks in Advance
Follow the blog tutorial for cake. It'll explain how to create associations and relationships between tables to let you do what is is you want, but in a nutshell, you need to create a relationship between History and Operator models and work from there.

Laravel Eloquent: merge model with Input

I would like to know how it is possible to merge data from Input::all() with a model and save the result.
To clarify: I would like to do something like below:
$product = Product::find(1); // Eloquent Model
$product->merge( Input::all() ); // This is what I am looking for :)
$product->save();
You should use update method:
$product->update(Input::all());
But I recommend to use only method instead
$product->update(Input::only('name', 'type...'));
Use the model's fill() method for greater control. This lets us change attributes after merging the values before we save:
$product->fill($request->all());
$product->foo = 'bar';
$product->save();
If we've properly defined the model's $fillable attributes, there's no need to use Input::only(...) (or $request->only(...) in newer versions).
In addition to Razor's answer, if you need to create a new model you can use:
$product = Product::create(Input::all());
I think the better way now is to use FormRequest and the validated function like this :
public function update(Product $product, ProductFormRequest $request)
{
$product->update($request->validated());
//...
}

php Yii Nested json array

First code:
$result=ResPlaces::model()->findall($criteria);
/*foreach($result as $value)
{
$model_name=ResRegistration::model()->findByAttributes(array('id'=>$value->user_id));
$model_image=ResImages::model()->findByAttributes(array('place_id'=>$value->id),array('limit'=>'1'));
}*/
}
echo CJSON::encode($result);
?>
i need to add model_name->company_name & $model_image->image
to my echo json array
Try to load the relations within the findAll so you don't need the foreach.
ResPlaces::model()->with('ResRegistration', 'ResImages')->together()->findAll($criteria);
For ResRegistration and ResImages use the relation names as defined in your model.
If you don't need all fields of these relations, you can specify a select in your $criteria.
See the guide for more info.
edit: I am not quite sure, why you cannot use relation. However you will need a loop, like you already have. Here is how you do it without relations:
First add the fields you want to use to your model. In this case
class ResPlaces extends CActiveRecord
{
public $name; // check that these do not collide with your models db fields
public $image;
[...]
}
In your controller do the loop like you did before:
foreach($result as $key => $value)
{
$result[$key]->name = ResRegistration::model()->findByAttributes(array('id' => $value->user_id));
// findByAttributes returns only one record, so you don't need the limit here
// if you want multiple records, you have to use findAllByAttributes
$result[$key]->image = ResImages::model()->findByAttributes(array('place_id' => $value->id), array('limit' => '1'));
}
That should do it. However I wouldn't recommend this way, because you have lots of additional database requests. If your $result is populated with say 100 records, you have in sum 200 additional queries which are not nessassary with a relation.
Note also that if you need these two other fields more often, it may be better to put these two queries which are now in the controller in your model. The afterFind() would be the right place.

Categories