Eloquent - Random from a existing list - php

I see that I can get a random row in Laravel 5 by:
Model::inRandomOrder()->get();
But I want to get all from Model and pick a random object from it like below.
$models = Model::all();
$model = $models->getRandom();
Any suggestion?

Yeah this should work:
$models = Model::all();
$model = $models->random();
Or even this:
$models = Model::get();
$model = $models->random();

two sugestions:
1. get your data twice:
$models = Model::all();
$model = Model::inRandomOrder()->get();
2. select a random row from the retrieved data:
$models = Model::all();
$model = $models[rand(0, count($models) - 1];

Related

How to use update() functionality in Laravel?

Inside my store function i have to search a name of a particular person, thus:
$person = DB::select("select p.* from persons p where concat_ws(', ' ,p.family_name,concat_ws(' ',concat_ws(' ',p.first_name,p.middle_name),p.third_name)) like ?", [$request['person_name']]);
If this person exist i have to update the person and this one works:
Person::where('id', $person[0]->id)->update(['status' => 'Active']);
but not this one:
$person[0]->status = 'Active';
$pArray = json_decode(json_encode($person[0]), true);
$per = new Person($pArray);
$per->update();
Since you have already created a new model instance, you would need to call the save() method.
$per = new Person($pArray);
$per->save();
Or, you can use update() to pass data into an existing model. But first, you need to retrieve the model you want to update.
$per = Person::find($pArray['id']);
$per->update($pArray);
Use your search query instead of mine. I think this will help you.
$result = User::where('id', $userId)->first();
$result->name = 'xyz';
$result->update();
For update data in laravel using model you need to pass where condition in it.
Sample example
$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
Hope this helps you!

Laravel, copy row to another table with eloquent relationship

I want to get the data form database table and create a new row in another table.
Which 1 PO have many PoProducts.
$_getPO = Order::find($id);
$_getPOProducts= OrderProducts::where('order_id', $id)->get();
$order_no = $_getPO->order_no;
$eta = $_getPO->eta;
$_Order = new DeliveryOrders();
$_Order->order_no = $order_no;
$_Order->eta = $eta;
$_Order->save();
$POProduct = array();
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[] = new DeliveryOrderProducts();
$POProduct[] = $_getPOProduct->order_id;
$POProduct[] = $_getPOProduct->item_id;
$POProduct[] = $_getPOProduct->qty;
$POProduct->save();
}
But, this output an error.
Call to a member function save() on array
Please help me. Thanks.
If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.
$user = User::findOrFail($id);
// replicate (duplicate) the data
$staff = $user->replicate();
// make into array for mass assign.
//make sure you activate $guarded in your Staff model
$staff = $staff->toArray();
Staff::firstOrCreate($staff);
Note: in case you're only duplicating on the same table replace Staff with User on this example.
You are trying to run the save method on the array but what you want is to use it on the array index instead.
Change your foreach to this and it should work (assuming columns are the same).
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = new DeliveryOrderProducts();
$POProduct[$i]->order_id = $_getPOProduct->order_id;
$POProduct[$i]->item_id = $_getPOProduct->item_id;
$POProduct[$i]->qty = $_getPOProduct->qty;
$POProduct[$i]->save();
}
You can shorten this by using forceCreate.
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}

Pass multiple IDs, get first record only in Laravel

How can I get only the first record using multiple IDs in Laravel? In the following code, $ids has three elements. I want to fetch the first record from table using these three IDs.
$ids = [16, 18, 20];
$listing = Listing::whereIn('id', $ids)->first();
If you want to get the first object with smallest id, you can do:
$listing = Listing::whereIn('id', $ids)->oldest('id')->first();
But better to do this:
$listing = Listing::find(min($ids));
If you want to get an object with the first ID in the array, do this:
$listing = Listing::find($ids[0]);
You can use either limit or oldest function of laravel see below query
$listing = Listing::whereIn('id', $ids)->limit(1)->get(); //using limit
OR
$listing = Listing::whereIn('id', $ids)->oldest('id')->first(); //using oldest()
A possible way to do this would be to sort the id column like so:
$listing = Listing::whereIn('id', $ids)->orderBy('id')->first();
I think you should try this:
$ids=[16,18,20];
foreach($ids as $id){
$listing[] = Listing::where('id', $id)->first();
}
Hope this work for you!

Not able to pass a variable in laravel

In the controller below, if I return $friendPosts (which has the post ids), the ids are shown in the view without problems.
But when I try to return the $sharedPosts (which has the whole row), nothing shows up in the view.
Controller
public function getProfile($email)
{
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::where('id', $friendPosts)->get();
return view('profile.index')
->with ('friendShares', $sharedPosts);
}
View
#foreach ($friendShares as $friendShares)
<p> {{$friendShares}}</p>
#endforeach
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::where('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::where('id', $friendPosts)->get();
should be
$myFriends = Auth::user()->friends()->lists('id');
$friendShares = Share::whereIn('user_id',$myFriends)->get();
$friendPosts = $friendShares->lists('post_id');
$sharedPosts = Post::whereIn('id', $friendPosts)->get();
You are working with more ids, not just one, so you have to use whereIn() which looks trough an array of values.
Next time it would be useful if you tell us what you actually wanted/tried to do with your code.

Yii 1.x, query in query DB selection

I have such sql query
SELECT * FROM tbl_role WHERE
tbl_role.id NOT IN (
SELECT tbl_user_role.roleID FROM tbl_user_role
WHERE tbl_user_role.userID = 35
)
AND
tbl_role.id NOT IN (
SELECT tbl_user_role_request.roleID FROM tbl_user_role_request
WHERE tbl_user_role_request.userID = 35 AND tbl_user_role_request.dateEnd IS NULL)
What is the best solution to make it in Yii-like code. How can i do this query using Yii 1.x ?
Assumptions:
tbl_role has a model named Role
tbl_user_role has a model named UserRole
tbl_user_role_request has a model named UserRoleRequest
Note that this will do 3 seperate queries but I believe this is the closest you can get without creating a total mess.
<?php
$userId = 35;
$roles = UserRole::findAllByCondition(array('userId' => $userId));
$roleIds = array_values(CHtml::listData($roles, 'roleId', 'roleId');
$roleRequests = UserRoleRequest::findAllByCondition(array('userId'=>$userId, 'dateEnd'=>null));
$roleRequestIds = array_values(CHtml::listData($roleRequest, 'roleId', 'roleId'));
$criteria = new CDbCriteria();
$criteria->addNotInCondition('id', $roleIds);
$criteria->addNotInCondition('id', $roleRequestIds);
$roles = Role::findAll($criteria);
I would use CDbCommand: http://www.yiiframework.com/doc/api/1.1/CDbCommand#queryAll-detail
Use the following code to fetch the data
$data = Yii::app()->db->createCommand('sql query')->queryAll;
And then you can use this dataset to create the dropDownList
$list = CHtml::listData($data, 'value field', 'text field');
echo $form->dropDownList($model, 'attribute', $list);

Categories