I wanted to retrieve session array and put into other model But throws `
Call to a member function pluck() on array
Controller I used :
$orders = $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');
How do i access the session data and put into other model?
Here is the response I get when i dd() the session :
array:1 [▼
0 => array:3 [▼
"school_id" => "4"
"order_date" => "11/25/2017"
"time_slot" => "10am - 8pm"
]
]
try like this,
$orders = $request->session()->get('order');
print_r($orders);
if you getting orders of school id array then you can get it by $orders['school_id']; and if you getting std object then you can retrieve it by $orders->school_id;
Use as per output of print_r(orders)
Then you can store it by
If std object ::
$order = new Order();
$order->school_id = $orders[0]->school_id;
$order->order_date = $orders[0]->order_date;
$order->time_slot = $orders[0]->time_slot;
$order->save();
If array ::
$order = new Order();
$order->school_id = $orders[0]['school_id'];
$order->order_date = $orders[0]['order_date'];
$order->time_slot = $orders[0]['time_slot'];
$order->save();
I would use the array_get helper.
https://laravel.com/docs/5.5/helpers#method-array-get
array_get($orders, 'school_id');
Additionally you can use a fallback as third parameter in case the value is not present in the session.
Session holds all data in Array and not Collection. Function pluck() can only be used for the collection.
Try doing array_get($orders, 'school_id'); as already mentioned by Marc or just $request->session()->get('order')['school_id'];
Call to a member function pluck() on array
Your $orders variable is an array so you can't use pluck. You can do $order['key'] to access their values. Or as others suggested, use the helper function array_get
it depends on how did you store it into session, so if you used push, then it will be stored as array.
anyways change your code to the following:
$orders = $request->session()-> pull('order',$defaultOrdersArrayCanBeHere);
$order = new Order();
$order->school_id = $orders['school_id'];
$order->order_date = $orders['order_date'];
$order->time_slot = $orders['time_slot'];
UPDATE:
Did you push it to session as so: session()->push('order', $order);
where:
$order = [
'school_id'=> $schoolId;
'order_date'=> $orderDate;
'time_slot'=> $timeSlot;
]
Related
Iam working on a laravel project which stores values to a DB entry in loop on meeting certain conditions.
This first creates an array if the entry is for the first time and adds a value to it. Henceforth, it recalls the array and keeps adding values to it.
if(is_null($lead->shown_to)) {
$a = array();
array_push($a, "lead 1");
$lead->shown_to = serialize($cart);
$lead->save();
} else {
$a=unserialize($lead->shown_to);
array_push($a, "lead 2");
$lead->shown_to = serialize($a);
$lead->save();
}
To be able to create an array and add distinct elements to it repeatedly.
Is there a way to first check if the element exists in it or not. If it does, just move ahead, else add it?
Thanks in advance.
There're a couple of methods you can use.
You can first look for the value on the DB if exists using a column from the database like:
$result = Model::where( 'column', 'value' );
if ( $result ) {
// update already exists
} else {
// create one
}
// Retrieve flight by name, or create it if it doesn't exist...
$flight = App\Flight::firstOrCreate(['name' => 'Flight 10']);
// Retrieve by name, or instantiate...
$flight = App\Flight::firstOrNew(['name' => 'Flight 10']);
Also it depends what you are looking for as firstOrCreate persists the value into the DB where firstOrNew just creates a new instance where you need to call save()
to check a value exists in an array you can use array_search(). this will return the value if exists. if not it returns false.
if(!array_search('lead 2', $a)) {
// array does't has 'lead 2' so,
array_push('lead 2', $a);
}
In Laravel I would take advantage of the Collections because they have a lot of helpful methods to work with.
I would do something like this:
OPTION 1
//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.
$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);
//Ask if the collection doesn't have the given value. If so, added it.
if (!$cart->contains($your_value)) {
$cart->push($your_value);
}
//Convert to array, serialize and store
$lead->shown_to = serialize($cart->toArray());
$lead->save();
OPTION 2
//Depending on the value of $lead->show, initialize the cart variable with the serialization of the attribute or and empty array and transform it to a collection.
$cart = collect($lead->shown_to ? unserialize($lead->shown_to) : []);
//Always push the value
$cart->push($your_value);
//Get the unique values, convert to an array, serialize and store
$lead->shown_to = serialize($cart->unique()->toArray());
$lead->save();
You can get more creative using the collections and they read better on Laravel
I think you can use updateOrCreate, if not exists it will create now, if exists, it will update it, so you can keep assigning value to shown_to property
$lead= App\Lead::updateOrCreate(
['name' => 'Lead 1'],
['shown_to' => serialize($a)]
);
if you wan to keep the existing shown_to better to use json data, so that you can do like
$lead= App\Lead::updateOrCreate(
['name' => 'Lead 1'],
['shown_to' => json_encode(array_push(json_decode($a), $newData))]
);
I'm trying to get Count of a table called TestRunList that has the foreign key the same as another table called Testrun meaning i want to get count of how many testrunlist that single testrun has in the same page i did a forloop to get testrun id for each testrunlist but it didn't seem to work i get this error
Cannot use object of type stdClass as array
heres my Code in the controller
$data = DB::table('TestRun')->get();
$runs=array();
for ($i=0;$i<sizeof($data);$i++)
{
$testrunID=$data[$i]['TestRunID'];
$Testrunlist=TestRunList::where('test_run_id',$testrunID)->count();
$runs[$i]=[
'Countruns'=>$Testrunlist
];
}
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
$data is a Collection, you can't access using array syntax
$data = DB::table('TestRun')->get();
$runs = [];
$data->each(function ($row) use ($runs) {
$runs[] = [
'Countruns' => TestRunList::where('test_run_id',$row-> TestRunID)->count()
];
});
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
Always use
print_r($data);
if it's object run echo $data->username if array run echo $data['username'];
So you know what type of data you're dealing with.
In my project, I use $request->all() to get params.
But $request->all() includes query thing. When I post a name => 1 to my API 'domain.com/api/users'
var_dump $request->all()
example :
[
'api/users' => null,
'name' => 1,
]
I want to remove like 'api/users' in my every $request->all(). What should I do?
You can use "except" or "only" method to filter your requests data.
$data = $request->except('key-that-you-dont-want-in-request');
// OR
$data = $request->only(['key-that-you-want-in-request', 'another-key']);
you can learn more about it here
https://laravel.com/docs/5.5/requests#retrieving-input
While I cannot guarantee that I perfectly understood the question but based on my understanding, to filter out fields that are not sent as part of the request, then using request()->only(['field', 'field_2']) should be sufficient given the instance stated in L5.5 upgrade notice about request->only method:
It means given the example I have, if field_2 is not present in the request, then it is discarded.
If you are on Laravel BEFORE 5.5 then $request->all() will give you only existing field, else for L5.5 you use request->only() You can give it a try and see how they work.
ON Laravel <= 5.4 and also L5.5
Finally, if you still get those fields as null then you can simply use array_filter($request_array) e.g:
$request_only = $request->all();
$requests_without_null_fields = array_filter($request_only);
This will remove all fields that are null preserving only fields that are not null.
Hope this is useful.
Since Laravel 5.5 you can also do it like this:
$data = $request->except(array_keys($request->query()));
Because $request->query() returns an array of only the query parameters.
You can collect all the request parameters being passed into one variable something like this:
$data = $request->only(['name', 'other_request_variables']);
An then use it as required.
Edit:
When you try to update the model, and you have need to pass all the variable from the views i.e. even if the old data is not updated with the new one you need to pass all the data from the form,
and in controller you can do something like this:
$user = User::find($request->id);
Get all the data and send back to views in the form and while sending the form data you need to send all the data:
$data = $request->(['id', 'name', 'city', 'address']);
$user = User::find($data['id']);
$user->name = $data['name'];
$user->city= $data['city'];
$user->address = $data['address'];
$user->save();
If you do not pass the old data then above code will update with the null values of the same.
And suppose you don't want to update with null values then you don't have to call it, suppose you call only name and id then just simply write:
$data = $request->(['id', 'name', 'city', 'address']);
$user = User::find($data['id']);
$user->name = $data['name'];
$user->save();
So in this case your city and address will be same with the old data, but in front end you don't know end user is updating what values, it can be either name, city or address you have to give flexibility to the end user.
Suppose you want to check the null values and then store it you can do something like this:
$data = $request->(['id', 'name', 'city', 'address']);
$user = User::find($data['id']);
$user->name = $data['name']: $data['name'] ? $user->name;
$user->city= $data['city'] : $data['city'] ? $user->city;
$user->address = $data['address'] : $data['address'] ? $user->address;
$user->save();
But in this case also you have to update with all parameters.
I have been having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work.
public function __construct(){
$product = array(1,2,3,4);
Session::push('cart', $product);
}
and then retrieve it in the view like this.
{{Session::get('cart')}}
However I keep getting an error like this.
htmlentities() expects parameter 1 to be string, array given
Any clues and advice on how to create a shopping cart that stores an array of items.
If you need to use the array from session as a string, you need to use Collection like this:
$product = collect([1,2,3,4]);
Session::push('cart', $product);
This will make it work when you will be using {{Session::get('cart');}} in your htmls. Be aware of Session::push because it will append always the new products in sessions. You should be using Session::put to be sure the products will be always updating.
You're storing an array in the session, and since {{ }} expects a string, you can't use {{Session::get('cart')}} to display the value.
The {{ $var }} is the same as writing echo htmlentities($var) (a very simple example).
Instead, you could do something like:
#foreach (Session::get('cart') as $product_id)
{{$product_id}}
#endforeach
If you use 'push', when initially creating the array in the session, then the array will look like this:
[
0 => [1,2,3,4]
]
Instead you should use 'put':
$products = [1,2,3,4];
$request->session()->put('cart', $products);
Any subsequent values should be pushed onto the session array:
$request->session()->push('cart', 5);
You can use .:
$product = array(1,2,3,4);
Session::put('cart.product',$product);
You can declare an array in session like
$cart = session('data', []);
$cart[] = $product;
session([ 'data' => $cart]);
return session('data', []);
you can also do it like that:
$data = collect($Array);
Session()->put('data', $data);
return view('pagename');
Currently i have table with posts, each posts has an id.
For a moment, only one posts exists, with id id = 92.
if i execute following code, i will get not false, but post with id=92:
$post = NewsPost::findFirst(['id' => 1]);
var_dump($post->id); // gives 92
Seems to be very strange logic..
What method could be used to retrieve post by id, and that will return false/throw exception if there is no such entity?
Try this:
$post = NewsPost::findFirst("id = 1");
or
$post = NewsPost::find(
array(
"conditions" => "id = ?0",
"bind" => array(0 => 1)
)
);
I use:
$instance = Model::findFirst($id);
Where $id is a primary key.
Use
NewsPost::findFirst(['id = 1']);
or
NewsPost::findFirst(1)
You should use:
NewsPost::findByid(1);
Where 'id' can be replaced by any of your model's properties. For example:
NewsPost::findByDescription('Description');
NewsPost::findByyourprop(yourpropval);
You can then count() the return value count($result) to determine if you received any records.
Note: I have also found the string searches to be case in-sensitive.