Apply certain condition or validation to restrict operation in Laravel Models - php

This is a category table I am using in my project using Laravel.
I have checks applied in the view files, for the category parent selection dropdown, so that the category itself and it's child's will not appear in the dropdown.
But form input fields value can be easily overridden using dev console.
Is there a way in models so that if parent id is equal to the category id itself or parent id is the child of current category then it will stop execution.
I have recently started laravel, a month ago, and still learning and building, so help here will be appreciated.

I was able to resolve the issue by overriding the update method in model -
Controller update method -
public function update(Request $request, $id)
{
$this->validate($request,
['name' => 'required',]);
$data = [];
$data = ['name' => Input::get('name'),
'parent' => !empty(Input::get('parent')) ? Posts_categories::find(Input::get('parent'))->id : NULL,];
$category = Posts_categories::find($id);
if(is_null($category))
{
Session::flash('flash-message', 'Category type with the given id does not exist.');
Session::flash('alert-class', 'alert-warning');
return redirect()->route('admin.post.category.index');
}
if($category->update($data)) {
Session::flash('flash-message', 'Category succesfully updated.');
Session::flash('alert-class', 'alert-success');
}
return redirect()->route('admin.post.category.index');
}
Model update method -
public function update(array $attributes = [], array $options = [])
{
$parent = SELF::find($attributes['parent']);
if($this->id == $parent->id || $this->id == $parent->parent)
{
Session::flash('flash-message', 'Invalid parent selection for category.');
Session::flash('alert-class', 'alert-warning');
return 0;
}
return parent::update($attributes, $options); // TODO: Change the autogenerated stub
}

Related

Laravel sync makes a duplicate date in pivot table if multiple images selected

Why does sync makes duplicate sync in the pivot table if i selects more than an image ?
In my application when adding a new competition a user can select one or more images/documents and the file path will be saved in the files table and sync the data into the competition_file pivot table.
Here's the create UI
Here's the store function on my controller
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, ['competition_id' => $competition,'team_id' => $request->team,'type' => $request->type,'share_type' => $request->share_type]);
$team->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))->with('success', 'Document updated.');
}
Here's the relationship codes in my model
public function documents()
{
return $this->belongsToMany(File::class,'competition_file','team_id','file_id')->wherePivot('type', 'document');
}
When i selectes more than one image as below it makes a duplicate in the competition_file table
This is how it saves in the competition_file pivot table with a duplicate data
But if Dump the data before sync while I have selected two images it shows only two array see below codes
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, ['competition_id' => $competition,'team_id' => $request->team,'type' => $request->type,'share_type' => $request->share_type]);
dd($forSync);
$team->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))->with('success', 'Document updated.');
}
Result
And if I remove the Dump and reloads the same page it syncs correctly
And if I retry without Dump and if I selects two image and save it creates a duplicate ?
I need to know what might be creating the duplicate sync.
I hope my question is clear, can someone please help me out.
Just for the benefit of subsequent visitors.
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, [
'competition_id' => $competition,
'type' => $request->type,
'share_type' => $request->share_type
]);
//If the implicit route model binding is not working
//if $team is null or you need to explicitly set the team
//selected by user and which is not passed as route param
Team::findOrFail($request->team)->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))
->with('success', 'Document updated.');
}

Laravel Form best way to store polymorphic relationship

I have a notes model. Which has a polymorphic 'noteable' method that ideally anything can use. Probably up to 5 different models such as Customers, Staff, Users etc can use.
I'm looking for the best possible solution for creating the note against these, as dynamically as possible.
At the moment, i'm adding on a query string in the routes. I.e. when viewing a customer there's an "Add Note" button like so:
route('note.create', ['customer_id' => $customer->id])
In my form then i'm checking for any query string's and adding them to the post request (in VueJS) which works.
Then in my controller i'm checking for each possible query string i.e.:
if($request->has('individual_id'))
{
$individual = Individual::findOrFail($request->individual_id_id);
// store against individual
// return note
}elseif($request->has('customer_id'))
{
$customer = Customer::findOrFail($request->customer_id);
// store against the customer
// return note
}
I'm pretty sure this is not the best way to do this. But, i cannot think of another way at the moment.
I'm sure someone else has come across this in the past too!
Thank you
In order to optimize your code, dont add too many if else in your code, say for example if you have tons of polymorphic relationship then will you add tons of if else ? will you ?,it will rapidly increase your code base.
Try instead the follwing tip.
when making a call to backend do a maping e.g
$identifier_map = [1,2,3,4];
// 1 for Customer
// 2 for Staff
// 3 for Users
// 4 for Individual
and so on
then make call to note controller with noteable_id and noteable_identifier
route('note.create', ['noteable_id' => $id, 'noteable_identifier' => $identifier_map[0]])
then on backend in your controller you can do something like
if($request->has('noteable_id') && $request->has('noteable_identifier'))
{
$noteables = [ 'Customers', 'Staff', 'Users','Individual']; // mapper for models,add more models.
$noteable_model = app('App\\'.$noteables[$request->noteable_identifier]);
$noteable_model::findOrFail($request->noteable_id);
}
so with these lines of code your can handle tons of polymorphic relationship.
Not sure about the best way but I have a similar scenario to yours and this is the code that I use.
my form actions looks like this
action="{{ route('notes.store', ['model' => 'Customer', 'id' => $customer->id]) }}"
action="{{ route('notes.store', ['model' => 'User', 'id' => $user->id]) }}"
etc..
And my controller looks this
public function store(Request $request)
{
// Build up the model string
$model = '\App\Models\\'.$request->model;
// Get the requester id
$id = $request->id;
if ($id) {
// get the parent
$parent = $model::find($id);
// validate the data and create the note
$parent->notes()->create($this->validatedData());
// redirect back to the requester
return Redirect::back()->withErrors(['msg', 'message']);
} else {
// validate the data and create the note without parent association
Note::create($this->validatedData());
// Redirect to index view
return redirect()->route('notes.index');
}
}
protected function validatedData()
{
// validate form fields
return request()->validate([
'name' => 'required|string',
'body' => 'required|min:3',
]);
}
The scenario as I understand is:
-You submit noteable_id from the create-form
-You want to remove if statements on the store function.
You could do that by sending another key in the request FROM the create_form "noteable_type". So, your store route will be
route('note.store',['noteableClass'=>'App\User','id'=>$user->id])
And on the Notes Controller:
public function store(Request $request)
{
return Note::storeData($request->noteable_type,$request->id);
}
Your Note model will look like this:
class Note extends Model
{
public function noteable()
{
return $this->morphTo();
}
public static function storeData($noteableClass,$id){
$noteableObject = $noteableClass::find($id);
$noteableObject->notes()->create([
'note' => 'test note'
]);
return $noteableObject->notes;
}
}
This works for get method on store. For post, form submission will work.
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Requests\NoteStoreRequest $request
* #return \Illuminate\Http\Response
*/
public function store(NoteStoreRequest $request) {
// REF: NoteStoreRequest does the validation
// TODO: Customize this suffix on your own
$suffix = '_id';
/**
* Resolve model class name.
*
* #param string $name
* #return string
*/
function modelNameResolver(string $name) {
// TODO: Customize this function on your own
return 'App\\Models\\'.Str::ucfirst($name);
}
foreach ($request->all() as $key => $value) {
if (Str::endsWith($key, $suffix)) {
$class = modelNameResolver(Str::beforeLast($key, $suffix));
$noteable = $class::findOrFail($value);
return $noteable->notes()->create($request->validated());
}
}
// TODO: Customize this exception response
throw new InternalServerException;
}

Yii2 - Override checkAccess in rest ActiveController

Product.supplierID = Supplier.supplierID
--------- ----------
|Product|---------|Supplier|
--------- ----------
|
| Supplier.supplierID = User.supplierID
|
---------
| User |
---------
Using the above table structure, the application uses sub-classes of ActiveController, with overridden prepareDataProvider to limit the index list of each Product a logged in User can see to those with matching supplierID values. Something like this in the actions() method of ProductController.
$actions['index']['prepareDataProvider'] = function($action)
{
$query = Product::find();
if (Yii::$app->user->can('supplier') &&
Yii::$app->user->identity->supplierID) {
$query->andWhere(['supplierID' => Yii::$app->user->identity->supplierID]);
}
return new ActiveDataProvider(['query' => $query]);
};
This works fine, however I'm looking to use checkAccess() to limit actionView() for a single Product.
At the moment, a logged in User can access a Product by changing the productID in the URL, whether or not the have the appropriate supplierID.
It looks like I can't access the particular instance of Product, to check the supplierID, until actionView() has returned which is when I want the check to happen.
Can I override checkAccess() to restrict access and throw the appropriate ForbiddenHttpException?
What about a function that checks if a model exist :
protected function modelExist($id)
{
return Product::find()
->where([ 'productID' => $id ])
->andWhere(['supplierID' => Yii::$app->user->identity->supplierID ])
->exists();
}
If productID is your Product Primary Key, then a request to /products/1 will be translated by yii\rest\UrlRule to /products?productID=1.
In that case, when productID is provided as a param, you can use beforeAction to make a quick check if such model exist & let the action be executed or throw an error if it doesn't :
// this array will hold actions to which you want to perform a check
public $checkAccessToActions = ['view','update','delete'];
public function beforeAction($action) {
if (!parent::beforeAction($action)) return false;
$params = Yii::$app->request->queryParams;
if (isset($params['productID']) {
foreach ($this->checkAccessToActions as $action) {
if ($this->action->id === $action) {
if ($this->modelExist($params['productID']) === false)
throw new NotFoundHttpException("Object not found");
}
}
}
return true;
}
update
As the question is about Overriding the checkAccess method in rest ActiveController I thought it would be useful to leave an example.
In the way how Yii2 REST was designed, all of delete, update and view actions will invoke the checkAccess method once the model instance is loaded:
// code snippet from yii\rest\ViewAction
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
The same is true for the create and index actions except that they won't pass any model instance to it: call_user_func($this->checkAccess, $this->id).
So what you are trying to do (throwing a ForbiddenHttpException when a user is trying to view, update or delete a product he is not its supplier) may also be achieved this way:
public function checkAccess($action, $model = null, $params = [])
{
if ($action === 'view' or $action === 'update' or $action === 'delete')
{
if ( Yii::$app->user->can('supplier') === false
or Yii::$app->user->identity->supplierID === null
or $model->supplierID !== \Yii::$app->user->identity->supplierID )
{
throw new \yii\web\ForbiddenHttpException('You can\'t '.$action.' this product.');
}
}
}

Laravel 5 How to perform validation in Controller to check for specific data in data collection

I want to perform custom validation in laravel 5, here is the concept. I have a category controller in which i want to delete a particular category. If category contains any other sub category i want to show validation error in laravel 5. For this concept i have create the program, but the program does not perform required validation. I am getting varies error like valiable not found or validation not performing or Undefined variable: struct. Below is the code that i am using to do that.
CategroyController destroy function, to delete record.
public function destroy(Request $request)
{
if(\Request::ajax()){
$validator = \Validator::make($request->all(), array());
$data = Configuration::findTreeParent($request->input('id'), 'Category');
$selected = $request->input('id');
foreach($data as $struct) {
$validator->after(function($validator) {
if ($selected == $struct->id) {
$validator->errors()->add('field', $request->input('configname').' cannot be assigned to its child category.');
}
});
}
if ($validator->fails()) {
return $validator->errors()->all();
} else{
return \Response::json(['response' => 200,'msg' => $validator->fails()]);
}
}
}
Please look into and help me out from this problem.
When using closure you need to pass a variable to its scope before using it. In your case $struct is not available in the scope of the closure you are passing to $validator->after().
So basically you have to pass the $struct to the closure.
// you can remove this line. $selected = $request->input('id');
$validator->after(function($validator) use ($struct) {
if ($request->input('id') == $struct->id) {
$validator->errors()->add('field', $request->input('configname').' cannot be assigned to its child category.');
}
});
To return the JSON response for the validation errors, update the following ode.
if ($validator->fails()) {
return \Response::json($validator->errors()->all(), 422);
}
Read about closure here.

Laravel Eloquent validation insert exception?

I've created a form which adds a category of product in a Categories table (for example Sugar Products or Beer), and each user has their own category names.
The Categories table has the columns id, category_name, userId, created_At, updated_At.
I've made the validation and every thing is okay. But now I want every user to have a unique category_name. I've created this in phpMyAdmin and made a unique index on (category_name and userId).
So my question is this: when completing the form and let us say that you forgot and enter a category twice... this category exist in the database, and eloquent throws me an error. I want just like in the validation when there is error to redirect me to in my case /dash/warehouse and says dude you are trying to enter one category twice ... please consider it again ... or whatever. I am new in laravel and php, sorry for my language but is important to me to know why is this happens and how i solve this. Look at my controller if you need something more i will give it to you.
class ErpController extends Controller{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('pages.erp.dash');
}
public function getWarehouse()
{
$welcome = Auth::user()->fName . ' ' . Auth::user()->lName;
$groups = Group::where('userId',Auth::user()->id)->get();
return view('pages.erp.warehouse', compact('welcome','groups'));
}
public function postWarehouse(Request $request)
{
$input = \Input::all();
$rules = array(
'masterCategory' => 'required|min:3|max:80'
);
$v = \Validator::make($input, $rules);
if ($v->passes()) {
$group = new Group;
$group->group = $input['masterCategory'];
$group->userId = Auth::user()->id;
$group->save();
return redirect('dash/warehouse');
} else {
return redirect('dash/warehouse')->withInput()->withErrors($v);
}
}
}
You can make a rule like this:
$rules = array(
'category_name' => 'unique:categories,category_name'
);

Categories