Laravel 9 query builder where clause has empty model id - php

I'm working on a Laravel 9 project and have created a custom validation rule called ValidModelOwnership which should check that the field a user is trying to add is owned by a model based on some values passed to it.
I've written the rule, but when debugging and outputting $model->toSql() the id is empty?
What am I missing?
My rule:
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Log;
class ValidModelOwnership implements Rule
{
/**
* The model we're checking
*/
protected $model;
/**
* Array of ownership keys
*/
protected $ownershipKeys;
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct($model, $ownershipKeys)
{
$this->model = $model;
$this->ownershipKeys = $ownershipKeys;
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
$model = $this->model::query();
$model = $model->where($this->ownershipKeys);
Log::debug($model->toSql());
if (!$model->exists()) {
return false;
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return "The :attribute field doesn't belong to you and/or your company.";
}
}
And my usage in my controller:
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store($company_id, $buyer_id, Request $request)
{
$this->authorize('create', BuyerTier::class);
$validator = Validator::make($request->all(), [
'name' => [
'required',
'string',
Rule::unique(BuyerTier::class)
->where('buyer_id', $buyer_id)
->where('company_id', $company_id)
],
'country_id' => [
'required',
'numeric',
new ValidModelOwnership(Country::class, [
['company_id', 80]
])
],
'product_id' => [
'required',
'numeric',
new ValidModelOwnership(Product::class, [
['company_id', 80]
])
],
'processing_class' => 'required|string',
'is_default' => [
'required',
'boolean',
new ValidDefaultModel(BuyerTier::class, $buyer_id)
],
'is_enabled' => 'required|boolean'
]);
if ($validator->fails()) {
return response()->json([
'message' => 'One or more fields has been missed or is invalid.',
'errors' => $validator->messages(),
], 400);
}
try {
$tier = new BuyerTier;
$tier->user_id = Auth::id();
$tier->company_id = $company_id;
$tier->buyer_id = $buyer_id;
$tier->country_id = $request->input('country_id');
$tier->product_id = $request->input('product_id');
$tier->name = trim($request->input('name'));
$tier->description = $request->input('description') ?? null;
$tier->processing_class = $request->input('processing_class');
$tier->is_default = $request->boolean('is_default');
$tier->is_enabled = $request->boolean('is_enabled');
$tier->save();
return response()->json([
'message' => 'Buyer tier has been created successfully',
'tier' => $tier
], 201);
} catch (\Exception $e) {
return response()->json([
'message' => $e->getMessage()
], 400);
}
}
I've hard-coded my id's to illustrate that even when set statically, it's not passed through:
[2023-01-19 09:40:59] local.DEBUG: select * from products where (company_id = ?) and products.deleted_at is null

Laravel (and most other frameworks) extract out variables when building SQL queries to prevent SQL injection.
So the following eloquent query:
User::where('name', 'Larry');
will become:
SELECT * FROM `users` WHERE `name` = ?
and it will also pass an array of bindings: ['Larry']. When SQL processes the query it replaces replaces the ? with the values in the bindings.
So if you want to see the full query you need to log the SQL and the bindings:
Log::debug($model->toSql());
Log::debug($model->getBindings());

Related

Laravel API Resourse returning relation only on 'collection' method

guys I'm new to Laravel. I currently building an API, and I have a couple of endpoints (the one that we will discuss are the Get All Tasks and Get Single Task)
The problem is that whenever I call the Get All Tasks endpoint it returns me the task resource + the user resource there. However when I call the Get Single Task endpoint it only returns me the TaskResource without the User inside of it. Any idea ?
Here is the code for the resourses
class TaskResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'estimate' => $this->estimate,
'status' => $this->status,
'type' => $this->type,
'user' => new UserResource($this->whenLoaded('user'))
];
}
}
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'avatar' => $this->avatar,
'tasks' => TaskResource::collection($this->whenLoaded('tasks'))
];
}
}
And here is how I get the Tasks in the controller.
https://prnt.sc/16q0rlh
The reason was that I was missing the 'with('user')' before the 'findOrFail' in my controller so ->
/**
* Description: Get single task
* Method: GET
* api/tasks/{id}
* #param TaskRequest $request
*/
public function actionGetTask(Request $request, $id) {
try {
return new TaskResource(Task::with('user')->findOrFail($request->route('id')));
} catch (\Exception $ex) {
return Response::json([
'success' => false,
'message' => 'There is no such id in the DB'
], 400);
}
}

Model Related Fields - Update and Create using FK

I have two tables. One for Users, one for Equipments.
I managed to make the search for username from other table, but now i want to create an equipment or to update an equipment directly to username, not by user_for_id. Is there any posibilty to do that ? Which would be the steps ? Thank you very much for any guidance.
First table : user_id - primary key, username, password ;
Second table: user_equip_id - primary key, phone_model, phone_model_series, phone_date_acq, nb_sg_model, nb_sg,_date_acq, display_model, display_series, display_date_acq, user_for_id - foreign key to user_id from table1
Controller:
<?php
namespace app\controllers;
use Yii;
use app\models\Equipment;
use app\models\EquipmentSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* EquipmentController implements the CRUD actions for Equipment model.
*/
class EquipmentController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['#'],
],
],
],
];
}
/**
* Lists all Equipment models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new EquipmentSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Equipment model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Equipment model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Equipment();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->user_equip_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Equipment model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->user_equip_id]);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing Equipment model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Equipment model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Equipment the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Equipment::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "equipment".
*
* #property int $user_equip_id
* #property string|null $phone_model
* #property string $phone_series
* #property string $phone_date_acq
* #property string $nb_sg_model
* #property string $nb_sg_series
* #property string $nb_sg_date_acq
* #property string $display_model
* #property string $display_series
* #property string $display_date_acq
* #property int $user_for_id
*
* #property User $userFor
*/
class Equipment extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'equipment';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq', 'user_for_id'], 'required'],
[['phone_date_acq', 'nb_sg_date_acq', 'display_date_acq'], 'safe'],
[['user_for_id'], 'integer'],
[['userFor'], 'safe'],
[['phone_model', 'phone_series', 'nb_sg_model', 'nb_sg_series', 'display_model', 'display_series'], 'string', 'max' => 50],
[['user_for_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_for_id' => 'user_id']],
[['userFor'], 'string', 'max' => 50],
//[['username'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['username' => 'username']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'user_equip_id' => 'User Equip ID',
'phone_model' => 'Phone Model',
'phone_series' => 'Phone Series',
'phone_date_acq' => 'Phone Date',
'nb_sg_model' => 'NB/GS Model',
'nb_sg_series' => 'NB/GS Series',
'nb_sg_date_acq' => 'NB/GS Date',
'display_model' => 'Display Model',
'display_series' => 'Display Series',
'display_date_acq' => 'Display Date',
'user_for_id' => 'User For ID',
'userFor.username' => 'Username',
];
}
/**
* Gets query for [[UserFor]].
*
* #return \yii\db\ActiveQuery|yii\db\ActiveQuery
*/
public function getUserFor()
{
return $this->hasOne(User::className(), ['user_id' => 'user_for_id']);
}
//public function getUsername()
//{
// print_r($equipment->userFor->username);die;
// }
/**
* {#inheritdoc}
* #return EquipmentQuery the active query used by this AR class.
*/
public static function find()
{
return new EquipmentQuery(get_called_class());
}
}
Model Search:
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Equipment;
/**
* EquipmentSearch represents the model behind the search form of `app\models\Equipment`.
*/
class EquipmentSearch extends Equipment
{
public $userFor;
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_equip_id', 'user_for_id'], 'integer'],
[['phone_model', 'phone_series', 'phone_date_acq', 'nb_sg_model', 'nb_sg_series', 'nb_sg_date_acq', 'display_model', 'display_series', 'display_date_acq'], 'safe'],
[['userFor'], 'safe'],
#[['username'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Equipment::find();
$query->joinWith(['userFor']);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['username'] = [
'asc' => ['user.username' => SORT_ASC],
'desc' => ['user.username' => SORT_DESC],
];
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'user_equip_id' => $this->user_equip_id,
'phone_date_acq' => $this->phone_date_acq,
'nb_sg_date_acq' => $this->nb_sg_date_acq,
'display_date_acq' => $this->display_date_acq,
'user_for_id' => $this->user_for_id,
]);
$query->andFilterWhere(['like', 'phone_model', $this->phone_model])
->andFilterWhere(['like', 'phone_series', $this->phone_series])
->andFilterWhere(['like', 'nb_sg_model', $this->nb_sg_model])
->andFilterWhere(['like', 'nb_sg_series', $this->nb_sg_series])
->andFilterWhere(['like', 'display_model', $this->display_model])
->andFilterWhere(['like', 'display_series', $this->display_series])
->andFilterWhere(['like', 'user.username', $this->userFor]);
return $dataProvider;
}
}
Thank you in advance for any guidance or help.

Search Filtering users by FK in gridview

I have users table containing : PK - id, username, password.
i have three tables ( laptop, display, phone) - id - FK, series, model
I have userequipmentmapping table containing : id - PK , user_id - FK( id from users table), laptop_id - FK (id from laptop table), phone_id - FK (id from phone table), display_id(id from dislpay table), start_date, end_date.
I want to search by user in my gridview from UserEquipmentMapping, but don't know where should i implement the search model, considering the username is passed from the users table by foreign key.
If you have any suggestions are appreciated. Thank You in advance !
Controller :
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
ModelSearch :
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\UserEquipmentMapping;
/**
* UserequipmentmappingSearch represents the model behind the search form of `app\models\UserEquipmentMapping`.
*/
class UserequipmentmappingSearch extends UserEquipmentMapping
{
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['id', 'user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
];
}
/**
* {#inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = UserEquipmentMapping::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'user_id' => $this->user_id,
'laptop_id' => $this->laptop_id,
'phone_id' => $this->phone_id,
'display_id' => $this->display_id,
'start_date' => $this->start_date,
'stop_date' => $this->stop_date,
]);
return $dataProvider;
}
}
Index :
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
['class' => 'yii\grid\SerialColumn'],
#'id',
'user.username',
#'laptop.laptop_model',
'laptop.laptop_series',
#'laptop_id',
#'phone.phone_model',
'phone.phone_series',
#'phone_id',
#'display.display_model',
'display.display_series',
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
Uncomment in your index view _search view. There are all fields from UserequipmentmappingSearch model. You can replace input fields with select fields for user, laptop and etc. Search model will do the other thing, all is in search function that fills your dataprovider

Laravel validation: rules in required_if

I have a select list, where the first option is disabled, that's way when the user does not choose an valid option, the result of the select list will not be in the request.
In the validation, the field required, if the value of an other field is for example : 1, in case not 1, the field is not required.
The code:
'city_id' => [
'required',
'integer',
Rule::in(City::availableCities()),
],
'district_id' => new DistrictValidation(request('city_id')),
How I can do that, the district_id throw the validation every time, regardless of, it is in the request, or not.
Thanks for answers,
Update:
Maybe you see clearly, if the DistrictValidation rule is here:
class DistrictValidation implements Rule
{
protected $city;
private $messages;
/**
* Create a new rule instance.
*
* #param $cityId
*/
public function __construct($cityId)
{
$this->city = City::find($cityId);
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
dd('here');
if (!$this->city) {
return false;
}
if (!$this->city->hasDistrict) {
return true;
}
$validator = Validator::make([$attribute => $value], [
$attribute => [
'required',
'integer',
Rule::in(District::availableDistricts()),
]
]);
$this->messages = $validator->messages();
return $validator->passes();
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return optional($this->messages)->first('district_id');
}
}
You can use required_if condition defined in laravel validation
Here is the link to the proper documentaion Laravel Validation
Validator::make($data, [
'city_id' => [
'required',
'integer',
Rule::in(City::availableCities()),
],
'district_id'=>[
'required_with:city_id,',
]
]);
Try this:
'city_id' => [
'nullable',
'numeric',
Rule::in(City::availableCities())
],
'district_id' => new DistrictValidation(request('city_id')),
try this :
$myValidations = [
"city_id" => [
"required",
"integer"
]
]
// if city_id exists in availableCities so add some rules
if(collect(city::availableCities)->contains(request("city_id"))){
$myValidations["district_id"] = new DistrictValidation(request('city_id'))
}
// validate request fields with $myValidations variable
try using the required_if validation where the field under validation must be present and not empty if the anotherfield field is equal to any value.
required_if:field,value,...
use it like:
$request->validate([
'city_id' => 'required|integer|Rule::in(City::availableCities())',
'district_id' => 'required_if:city_id,1',
]);
try to read more laravel validation here

on calling new created controller function it navigates to 404 error page

in yii2 advanced template site Controller is working fine. When calling a function in new controller it is navigating to 404 error page.
I created model using model generator and create a crude for the model.
This is my controller
namespace backend\Controllers;
use Yii;
use common\models\PackageTable;
use common\models\PackageTableSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* PackageTableController implements the CRUD actions for PackageTable model.
*/
class PackageTableController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all PackageTable models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new PackageTableSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single PackageTable model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new PackageTable model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new PackageTable();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->package_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing PackageTable model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->package_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing PackageTable model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the PackageTable model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return PackageTable the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = PackageTable::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
This is my model
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "package_table".
*
* #property integer $package_id
* #property string $package_name
* #property string $description
* #property integer $amount
* #property integer $status
* #property string $created_on
* #property string $updated_on
*/
class PackageTable extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'package_table';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_name', 'description', 'amount', 'status'], 'required'],
[['description'], 'string'],
[['amount', 'status'], 'integer'],
[['created_on', 'updated_on'], 'safe'],
[['package_name'], 'string', 'max' => 250],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'package_id' => 'Package ID',
'package_name' => 'Package Name',
'description' => 'Description',
'amount' => 'Amount',
'status' => 'Status',
'created_on' => 'Created On',
'updated_on' => 'Updated On',
];
}
}
This is my model search
<?php
namespace common\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PackageTable;
/**
* PackageTableSearch represents the model behind the search form about `common\models\PackageTable`.
*/
class PackageTableSearch extends PackageTable
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['package_id', 'amount', 'status'], 'integer'],
[['package_name', 'description', 'created_on', 'updated_on'], 'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = PackageTable::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'package_id' => $this->package_id,
'amount' => $this->amount,
'status' => $this->status,
'created_on' => $this->created_on,
'updated_on' => $this->updated_on,
]);
$query->andFilterWhere(['like', 'package_name', $this->package_name])
->andFilterWhere(['like', 'description', $this->description]);
return $dataProvider;
}
}
Although php namespaces are case-insensitive, autoloader in your case is likely case-sensitive.
At the top of your controller namespace mentioned as
namespace backend/Controllers;
but in advanced template all directories are in lower case. So try to change this line to
namespace backend/controllers;

Categories