Use of undefined constant id - assumed 'id' in laravel 5.4 - laravel-5.4

What is this error?
Use of undefined constant id - assumed 'id'
public function update(Request $request)
{
SubmitApplication::where('id', $request->get(id))->update(['approved' => true]);
return redirect()->back();
}

Strings need to be wrapped in quotes, otherwise PHP assumes it's a name of a constant, hence the error.
Replace
$request->get(id)
with
$request->get('id')

Related

Want to get maximal value, but query doesn't work

I try to program a query in Yii2, which shows me the highest value of the database. Unfortunately, I get error message:
"Call to a member function all() on string"
How to patch this problem?
<?php
namespace app\controllers;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\Country;
class CountryController extends Controller
{
public function actionIndex()
{
$query = Country::find();
$countries = $query->select('population')->max('population')
->all();
return $this->render('index', [
'countries' => $countries,
]);
}
}
?>
You can use this
$query = Country::find();
$countries = $query->select('population')->max('population');
Also you can use
$query = Country::find();
$countries=$query->select('max(population) as `population`')->one();
It will help you :)
You have put as 'population' or other field name in table to assign value in second query.
According to your code example, you are calling all() on the result of max(), which according to the error message is returning a string.
max() is returning the maximum value, so you probably just need to drop ... ->all().
Try this:
$countries = $query->select('population')->max('population');

Eloquent where clause to use related model's column when using with() -laravel 4

I have 2 models
Truck
class Truck extends \Eloquent {
// Add your validation rules here
public static $rules = [
'trucktype_id' => 'required',
'weight'=> 'required',
'truck_no'=> 'required'
];
// Don't forget to fill this array
protected $fillable = ['trucktype_id','weight','picture_path','remarks','truck_no'];
public function TruckType(){
return $this->belongsTo('TruckType','trucktype_id');
}
}
TruckType
class Trucktype extends \Eloquent {
// Add your validation rules here
public static $rules = array(
'type' => 'required|unique:trucktypes,type',
'max_weight' => 'required'
);
// Don't forget to fill this array
protected $fillable = ['type','max_weight'];
}
I need to lookup related table records i.e TruckType
$trucksobj = Truck::with('TruckType');
if($truck_no!="")
$trucksobj->where("truck_no",'=',$truck_no);
if($start_date!="" && $end_date!="")
$trucksobj->whereBetween('created_at', array($start_date, $end_date));
if($truck_type!="")
$trucksobj->where("trucktype_id",'=',$truck_type);
if($overweight=="on")
$trucksobj->where('TruckType.max_weight', '>=', 0);
But the above query didnt resolve TruckType.max_weight and throws following error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TruckType.max_weight' in 'where clause' (SQL: select count(*) as aggregate from trucks where TruckType.max_weight >= 0)
I think you misunderstand how with() actually works. It is only used to alleviate the N+1 query problem, and does not make the contents of the table available for querying. After your first query has ran to select all of the trucks, the with() simply causes the following query to be automatically ran:
select * from TruckType where TruckType.id in (...)
Here the list at the end will contain all of the different truck.trucktype_id values that were found in your first query, and then they'll automatically be available for you to use via $truck->TruckType->{property} etc.
Now, if you actually have a look at the query that's being generated for you, you can clearly see that there is no TruckType table referenced anywhere:
select count(*) as aggregate from trucks where TruckType.max_weight >= 0
This is why the error is being thrown.
You have two options:
(1) Use a join
$trucksobj = Truck::with('TruckType')->join('TruckType', 'truck.trucktype_id', '=', 'TruckType.id')->where('TruckType.max_weight', '>=', 0);
(2) Use whereHas() to place a constraint on your relationship
$trucksobj = Truck::with('TruckType')->whereHas('TruckType', function($q) {
$q->where('max_weight', '>=', 0);
});
If you don't actually need to know anything about the truck type, and you only want to use it to sieve through the trucks, then you can get rid of with('TruckType') and just keep the rest of the query.

cakephp - Greater the (>) not working

i am working on a cakephp 2.x . i want to get the specific field result of a user if the date is greater then the date i specify. but unfortunately the query is not working and i am getting an error
here is the query which i am trying
public function getLicense($userid)
{
return $this->field('license', array(
'idUser' => $userid,
'registrationDate >'=>2013-08-20
));
}
i am not sure whether this query is right because i never used greater then sign before in cakephp. help me to correct the query
You're right, just forgot that date is a string and missing quotes. Closed it in quotes:
public function getLicense($userid) {
return $this->field('license', array(
'idUser' => $userid,
'registrationDate >' => "2013-08-20"
));
}

Passing $id to a controller

Im passing the id of an user to a controller. This id is used to fill a field of another Entity so this entity can know where it belongs to. The code of the controller is
public function nuevamedidaAction($id, Request $peticion){
$em = $this->get('doctrine')->getEntityManager();
$medida = new \Goodday\PreditBundle\Entity\Medida;
$medida->setHijo($id);
$form = $this->createForm(new \Goodday\PreditBundle\Form\MedidaType(), $medida);
$form->handleRequest($peticion);
if ($form->isValid()) {
$em->persist($medida);
$em->flush();
return $this->render('PreditBundle:Default:test2.html.twig');
}
return $this->render('PreditBundle:Medida:newmedida.html.twig', array('form' => $form->createView(), 'error' => $form->getErrors()));
}
now the field "hijo" in my entity looks like:
/**
* #ORM\ManyToOne(targetEntity="Hijo", inversedBy="medidas", cascade={"remove"})
* #ORM\JoinColumn(name="hijo_id", referencedColumnName="id")
*/
protected $hijo;
It returns me the following error
"Catchable Fatal Error: Argument 1 passed to Goodday\PreditBundle\Entity\Medida::setHijo() must be an instance of Goodday\PreditBundle\Entity\Hijo, string given, called in C:\Users\Diego\Desktop\Practicas\predit\src\Goodday\PreditBundle\Controller\HijoController.php on line 74 and defined in C:\Users\Diego\Desktop\Practicas\predit\src\Goodday\PreditBundle\Entity\Medida.php line 461"
Thanks for all your answers
The error is clear: Argument 1 passed to Goodday\PreditBundle\Entity\Medida::setHijo() must be an instance of Goodday\PreditBundle\Entity\Hijo, string given
You must pass an Hijo object to the method setHijo
$hijo = $em->getRepository('GooddayPreditBundle:Hijo')->find($id);
$medida->setHijo($hijo);
Hope it's helpful.
Best regard.

GET parameters validation

Every Yii2 guide/tutorial that I have come across ignores the validation of GET parameters. I'm wondering why.
To give an example, take a look at this code:
public function actionView($id)
{
/* #var $model ActiveRecord */
$model = Model::findOne($id);
if ($model) {
return $this->render('view', ['model' => $model]);
} else {
throw new \yii\web\NotFoundHttpException();
}
}
I understand that if you pass invalid argument to findOne() method, it will just return null and nothing bad happens. But is this really the best practice? I have always tried to be very careful with user input and the way I see it, user input should be validated immediately before performing any operations such as DB calls. Even if it's GET data, not just POST data.
public function actionView($id)
{
/* #var $model yii\base\DynamicModel */
$model = DynamicModel::validateData(['id' => $id], [
'idValidation' => ['id', integer]
]);
if ($model->hasErrors()) {
throw new \yii\web\BadRequestHttpException();
}
/* #var $model yii\db\ActiveRecord */
$model = Model::findOne($id);
if ($model) {
return $this->render('view', ['model' => $model]);
} else {
throw new \yii\web\NotFoundHttpException();
}
}
What do you think? Is my approach reasonable or overkill and unnecessary?
If you're using action parameters, you don't need to validate this parameters again (unless you have specific reason for it, like closed dictionary of allowed values, but I guess this is not the case). If your action uses signature like actionView($id) Yii will ensure few things before further processing of action:
$_GET['id'] exist, so $id will never be null. If someone will try to call this action without id value in GET, he will get BadRequestHttpException exception without calling action.
$_GET['id'] is a scalar. It means that if someone will try to pass array as id, he will get BadRequestHttpException exception without calling action.
So at this point in action you may be sure that $id is string. This is enough for findOne() safety. Even if you expect integer and someone pass blablabla as $id, it does not matter - he will get NotFoundHttpException anyway since there is no record with blablabla as id (this is impossible - blablabla in not a valid integer) - there is no need for extra check here. So default examples generated by Gii or from Yii documentation are safe. So your approach is a overkill and it is completely unnecessary.
Situation may change when $id can be array, since array allows much more powerful syntax. You need to take extra attention when:
You're explicitly allowing array as action param: actionView(array $id).
You're not using action params and using $_GET params directly: $id = $_GET['id'] or $id = Yii::$app->request->get('id') - in these cases $id can be array even if you're expecting scalar.
In this case $id value may be quite surprising. For example attacker may pass multiple IDs even if you're expecting single ID. Or filter by specified field instead of primary key, by passing ['email' => 'user#example.com'] as a $id - users will be searched by email field (or any other) even if intention is to filter only by ID. In such cases you should validate this array to make sure that it contains only expected values.
In older version this also allows for SQL Injection, since columns names (keys in array) were not escaped (this is still valid for where()). See 2.0.15 release announcement with some explanation.