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.
Related
I have a data coming from the HTML Page. And i want to check whether the date and the place values already exists. If they exists, it should throw an error saying Data is already present, if those date and place data is not there it should allow the user to save it.
Here is the code which i have written to save it,
public function StoreSampling(Request $request)
{
$date = Carbon::createFromFormat('d-m-Y', $request->input('date'))->format('Y-m-d');
$doctorname = Input::get('doctorselected');
$product = Input::get('product');
$product= implode(',', $product);
$quantity = Input::get('qty');
$quantity =implode(',',$quantity);
$representativeid = Input::get('representativeid');
//Store all the parameters.
$samplingOrder = new SamplingOrder();
$samplingOrder->date = $date;
$samplingOrder->doctorselected = $doctorname;
$samplingOrder->products = $product;
$samplingOrder->quantity = $quantity;
$samplingOrder->representativeid = $representativeid;
$samplingOrder->save();
return redirect()->back()->with('success',true);
}
I searched some of the Stack over flow pages. And came across finding the existence through the ID And here is the sample,
$count = DB::table('teammembersall')
->where('TeamId', $teamNameSelectBoxInTeamMembers)
->where('UserId', $userNameSelectBoxInTeamMembers)
->count();
if ($count > 0){
// This user already in a team
//send error message
} else {
DB::table('teammembersall')->insert($data);
}
But i want to compare the date and the place. And if they are not present, i want to let the user to save it. Basically trying to stop the duplicate entries.
Please help me with this.
There are very good helper functions for this called firstOrNew and firstOrCreate, the latter will directly create it, while the first one you will need to explicitly call save. So I would go with the following:
$order = SamplingOrder::firstOrNew([
'date' => $date,
'place' => $place
], [
'doctorname' => Input::get('doctorselected'),
'product' => implode(',', Input::get('product')),
'quantity' => implode(',',Input::get('qty')),
'representativeid' => Input::get('representativeid')
]);
if($order->exists()) {
// throw error
return;
}
$order->save();
// success
You need to modify your query to something like this:
$userAlreadyInTeam = SamplingOrder::where('date', $date)
->where('place', $place) // I'm not sure what the attribute name is for this as not mentioned in question
// any other conditions
->exists();
if (userAlreadyInTeam) {
// Handle error
} else {
// Create
}
You do not need to use count() as your only trying to determine existence.
Also consider adding a multi column unique attribute to your database, to guarantee that you don't have a member with the same data and place.
The best way is to use the laravel unique validation on multiple columns. Take a look at this.
I'm presuming that id is your primary key and in the sampling_orders table. The validation rule looks like this:
'date' => ['unique:sampling_orders,date,'.$date.',NULL,id,place,'.$place]
p.s: I do not see any place input in your StoreSampling()
I am creating a web site. So , I have stored data in the database. Now I want to view data from two different tables. Then I tried a method like below. But , it gives me this error -
Trying to get property 'firstname' of non-object (View: D:\wamp64\www\cheapfares\resources\views\invoices\des.blade.php)
But , clearly firstname is in the database table.
How can I Fix this ??
Controller page. ( InvoicesController.blade.php )
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
$twoar = [];
$twoar['inv'] = $invoice;
$twoar['trms'] = $tr;
return view('invoices.des', ['twoar' => $twoar]);
}
View page. ( des.blade.php )
{{$twoar['inv']->firstname}}
{{$twoar['trms']->topic}}
Route.
Route::get('/invoice/adminuser-invoice/{invoiceno}', [
'uses' => 'InvoicesController#adminuserinvoice',
'as' => 'invoice.adminuser'
]);
Although casting the response to Array might be a suitable solution, the cause of your exception most likely lies in not having a valid entry in the database.
You can improve your code like this to mitigate that:
public function userinvoice($terms, $invoiceNo)
{
// Load invoice, or throw ModelNotFoundException/404 without valid entries.
$invoice = Invoice::where('invoicereference', $invoiceNo)->firstOrFail();
// load the terms.
$terms = DB::table('termsandconditions')
->where('topic', $terms)->first();
return view('invoices.des', compact('invoice', 'terms'));
}
In this example I made $terms and $invoiceNo obligated arguments in the route. To ensure the query will provide proper results. In addition an Invoice entry is now required with firstOrFail(), the terms is optional. Instead of assigning both variables to an array, I'm sending them both to the view so you can assert their value properly without cluttering using array key access.
Your view:
{{$invoice->firstname}}
{{$terms->topic}}
Try this below code:
public function userinvoice($terms = '',$invoiceNo = '')
{
$invoice = Invoice::where('invoicereference', $invoiceNo)->get()->first();
$tr = DB::table('termsandconditions')
->where('topic', $terms)->get()->first();
return view('invoices.des', ['tr'=>$tr,'invoice'=>$invoice]); //Directly pass the mulitple values into the view
}
And your view page like this:
{{$invoice->firstname}}
{{$tr->topic}}
Its may help for you friend.
In some part of my app I need to update only the field is_active of some table with a lot of fields. What is the best approach to update only this field and avoid the validations and requiriments of all other fields?
And if you want to update particular row only , use this:
$users= TableRegistry::get('Users');
$user = $users->get($id); // Return article with id = $id (primary_key of row which need to get updated)
$user->is_active = true;
// $user->email= abc#gmail.com; // other fields if necessary
if($users->save($user)){
// saved
} else {
// something went wrong
}
See here (Updating data in CakePHP3).
This will work:
$users = TableRegistry::get('Users');
$query = $users->query();
$query->update()
->set(['is_active' => true])
->where(['id' => $id])
->execute();
http://book.cakephp.org/3.0/en/orm/query-builder.html#updating-data
When you don't want callbacks to be triggered, just use updateAll()
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
Using the example here: http://book.cakephp.org/3.0/en/orm/database-basics.html#running-update-statements. Run the code below to update all records in table_name_here table with a new value for is_active column.
use Cake\Datasource\ConnectionManager;
$connection = ConnectionManager::get('default');
$connection->update('table_name_here', ['is_active' => 'new_value_here']);
I faced this issue when upgrading my project from 2.10 to 3.x.
In 2.10 you could update a single field using:
$this->Menus->saveField('css', $menucss);
But since this method was deprecated, we do as below now, considering that callbacks will not be triggered:
$this->Menus->updateAll(['css' => $menucss], ['id' => $menu_id]);
The other answers don't use internationalization and other models props, callbacks, etc.
I think this is because of the query builder, it does not use the models and so their behaviors, therefore you should use:
$this->loadModel('Inputs');
$input = $this->Inputs->find()->where(['`key`' => $this->request->data['id']])->first();
$this->Inputs->patchEntity($input, ['prop' => $this->request->data['prop']]);
if ($this->Inputs->save($input)) {
die(json_encode(true));
} else {
die(json_encode(false));
}
I do have the invitations table set up and in the database. I use it for other purpose such as adding more...
my goal: update the first record with a new value to a field:
I tried:
$invitation = new MemberInvitation();
$invitation1 = $invitation->find(1);
$invitation1->status = 'clicked';
$invitation1->save();
And also:
$invitation1 = \App\Model\MemberInvitation::find(1);
$invitation1->status = 'clicked';
$invitation1->save();
both ended with:
Creating default object from empty value
EDIT:
This piece of code worked and updated my records correctly -- I just can't do it via Eloquent's model:
\DB::table('member_invitations')->where('id', '=', $member_invitation->id)
->update(array('status' => 'clicked', 'member_id' => $member->id));
what am I missing?
Try this.
$invitation = MemberInvitation::findOrFail(1);
$invitation->status = 'clicked';
$invitation->save();
If that doesnt work, please show your model
find(1) doesn't mean "give me the first record", it means "give me the first record where id = 1". If you don't have a record with an id of 1, find(1) is going to return null. When you try and set an attribute on null, you get a PHP warning message "Creating default object from empty value".
If you really just want to get the first record, you would use the first() method:
$invitation = \App\Model\MemberInvitation::first();
If you need to get a record with a specific id, you can use the find() method. For example, to translate your working DB code into Eloquent, it would look like:
$invitation = \App\Model\MemberInvitation::find($member_invitation->id);
$invitation->status = 'clicked';
$invitation->member_id = $member->id;
$invitation->save();
The answer is obvious based on your reply from May 15th.
Your "fillable" attribute in the model is empty. Make sure you put "status" in that array. Attributes that are not in this array cannot up modified.
I've been trying all night to update a record like this:
$r = $this->Question->read(NULL, $question['Question']['id']);
debug($r);// This is a complete Question array
$this->Question->set('status', 'version');
$s = $this->Question->save();
//$s = $this->Question->save($r['Question']);//this also doesn't work
debug($s); // = False every time!! Why??
exit;
The two comments show variations I've tried but didn't work either.
#Dipesh:
$this->data = $this->Question->read(NULL, $question['Question']['id']);
$this->Question->status = 'version';
$s = $this->Question->save($this->data);
debug($s);
exit;
#Dipesh II:
$this->request->data = $this->Question->read(NULL, $question['Question']['id']);
debug($this->data);
//$this->Question->status = 'version';
$this->request->data['Question']['status'] = 'version';
$s = $this->Question->save($this->request->data);
//$s = $this->Question->save($r['Question']);
debug($s);
exit;
#Dipesh III:
(removed)
cakePHP provide a method called set() in both Models::set() as well as in Controller::set();
About Controller::set()
This method is used to set variables for view level from any of the controller method. For example fetching records and from models and setting them for views to display it to clients, like this
$data = $this->{ModelName}->find('first');
$this->set('dataForView',$data) // now you can access $data in your view as $dataForView
About Model::set()
This method is used to set data upon a model, the format of the array that will be passed must be same as that used in Model::save() method i.e. like this
$dataFormModel = array('ModelName'=>array('col_name'=>$colValue));
$this->{ModelName}->set($dataForModel);
Model::set() will accept its parameter only in this format, once successfully set you can do following
validate this data against the validation rules specified in model directly like this
$isValid = $this->ModelName->validate();
save/update data by calling Model::save()
Use $this->data instead of $r
Example
$this->data = $this->Question->read(NULL, $question['Question']['id']);
$this->set is used to set variable value and pass it to view so view can access it where as $this->data represent the data to be stored in database.
If You're using Cake 2.0 then replace $this->data which is read only in Cake 2.0 to $this->request->data.
It's not very "automagical" but I was able to get this working like this:
$set_perm_id = 42;//who cares
$data = array(
'Question'=> array(
'id'=> $question['Question']['id'],
'perm_id'=> $set_perm_id,
'status'=>'version'
)
);
$s=$this->Question->save($data);
Basically I'm just building the data array manually. If anyone knows why this works instead of what I was doing before, I'd love to hear it.
Just try these lines..
$this->Question->id = $question['Question']['id'];
$this->Question->set('status','version');
$this->Question->save();
OR
$aUpdate["id"] = $question['Question']['id'];
$aUpdate["status"] = "version";
$this->Question->save($aUpdate);