I have two tables: assignments table(columns assignment_id, Staff Name, asset_id, department, date, status), and an assets table (columns asset_id, tag_name, serial_number, model_number, color). The asset table columns are linked with the assignments table. I want to perform an insertion into the assignments table but before the insertion, i want to check if the asset_id already exists in the assignments table & if it's status = 'Active' then the insertion should throw an error/shouldn't happen.
AssignmentsController
class AssignmentController extends Controller
{
public function assignment(){
$assignments = Assignment::all();
return view('assignment/index', ['assignments' => $assignments]);
}
public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignments = new Assignment;
$assignments ->assignment_id = $request->input('assignment_id');
$assignments ->staff_id = $request->input('staff_id');
$assignments ->asset_id = $request->input('asset_id');
$assignments ->department_id = $request->input('department_id');
$assignments ->date = $request->input('date');
$assignments ->status = $request->input('status');
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
$assignments ->save();
return redirect('/assignment/index') ->with('info', 'New Assignment Saved Successfully!');
}
Assginment.php
class Assignment extends Model
{
protected $primaryKey = 'assignment_id';
public function asset()
{
return $this->belongsTo('App\Asset', 'asset_id');
}
}
The below variable and if statement in the AssignmentsController always throws the error in the if statement whether it's true or not and the insertion doesn't happen but when the whole statement is cleared, the insertion happens.
$count = Assignment::where('status', '=' ,'Active' )->
where('asset_id', '=' ,$assignments->asset_id)->
count();
if($count) {
abort(405, 'Trying to assign an already assigned asset');
}
So i want a way to check if the the record to be inserted already exists with conditions as if asset_id exists then check for it's status if it's ='Active' then throw an error but if not then insertion happens. Please help if you understand it. Thanks in advance.
You can just do:
public function add(Request $request){
$this->validate($request, [
'assignment_id' => '',
'staff_name' => 'required',
'asset_id' => 'required',
'department' => 'required',
'date' => 'required',
'status' => 'required'
]);
$assignment = Assignment::firstOrNew([
"status" => "Active",
"asset_id" => $assignments->asset_id
], $request->all());
abort_if($assignment->exists(), 405, 'Trying to assign an already assigned asset');
$assignment->save();
return redirect('/assignment/index')
->with('info', 'New Assignment Saved Successfully!');
}
The Solution
$count = Assignment::where('asset_id', '=' ,$assignments->asset_id)->
where('status', '=' ,'Active')->
count();
if($count == 1 && $assignments->status != 'Disable') {
abort(405, 'Trying to assign an already assigned asset');
}
The mistake in my code: I was counting all Assignments and if there is any active status i got an error....I needed to check exactly that assignment which i want to assign which was either active or disable then the assignment should occur or not pertaining it's status(active/disable). Thanks Y'all esp apokryfos.
Related
So, I have a pivot table called user_filmscores, where the users can ''follow (watching, dropped, hold-on...)'' a film and add a rating on it.
In the userController I have this function:
public function userFilm(Request $request){
$data = $request->all();
$validator=Validator::make($data,[
'user_id' => 'required',
'film_id' => 'required',
'state' => 'required',
'score' => 'nullable'
]);
if($validator->fails()){
return response()->json([
'ok' => false,
'error' => $validator->messages(),
]);
}
$film = Film::find($data['film_id']);
$user = User::find($data['user_id']);
$filmId=$data['film_id'];
$userId=$data['user_id'];
//Check if the relationship exists (I tried many methods but always the same result with false)
/*$hasFilm = User::where('id', $data['user_id'])->whereHas('film', function ($q) use ($filmId) {
$q->where('id', $filmId);
})->exists();*/
$hasFilm = $user->film()->where('film_id', '=', $filmId)->exists();
/*$user->film()->sync($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);*/
if(User::where('id', $userId)->where('id')){
$user->film()->attach($film->getKey(), [
'film_id' => $data['film_id'],
'user_id' => $data['user_id'],
'state' => $data['state'],
'score'=> $data['score']
]);
}else{
$user->film()->detach($film->getKey());
}
}
In the final part of the code, I want to check if the relationship between the user and the film exists, to make an action or another. But when I try to check if the relationship exists, it always returns me a false.
I thought to do it like, if there is a relationship, first delete the old relationship, and then create a new one.
I don't know if there is a better way to do it.
User model has this function:
public function film(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'user_id', 'film_id', 'state', 'score');
}
Film model has this function:
public function user(){
return $this->belongsToMany('App\Models\Film', 'user_filmscores', 'film_id', 'user_id', 'state', 'score');
}
Users table:
Films table:
User_filmscores table:
Hi I am using Request to validate my form.
listingId = 20
categoryType ='listing-category'
I have tried two ways to validate the form. First is
'title' => 'required|min:2|max:255|unique:terms,title,'.$listingId.',id,type,'.$categoryType,
And the second one is
if($this->method() != 'PUT')
{
$uniqueTitleValidation = Rule::unique('terms')->where('type', $categoryType);
}
else
{
$uniqueTitleValidation = [];
$uniqueTitleValidation = Rule::unique('terms')->ignore($listingId)->where('type', $categoryType);
}
and in validation
'title' => [
'required',
'min:2',
'max:255',
$uniqueTitleValidation
],
while creating a new entry it Is working fine. But ignoring the type I guess while updating and throw me already exists error.
This is my DB table
Now as you can see I want to check for listing-category. But I think it also checking for category type.
Note: I am using laravel 5.8
Try below example is cleaner and should work.
$uniqueTitleValidation = Rule::unique('terms')
->where(function ($query) use($categoryType, $listingId){
if($this->method() != 'PUT') {
return $query->where('type', '=', $categoryType);
}
return $query->where([
['type', '=', $categoryType],
['id', '<>', $listingId] // ignore this id and search for other rows
]);
});
Create a rule in your UpdateRequest under App\Http\Requests
Just add the below code.
public function rules()
{
return [
'title' => [
'required',
'string',
Rule::unique('terms', 'title')->whereNull('deleted_at')->ignore($this->listing),
],
];
}
My project requires that the admin has to approve the item uploaded by the user in order for this item to be seen in the website as in sort of validation or some kind of keeping everything under control.
so in the Item table, I have a field called (status) and has a default value = (denied).
$table->enum('status',['available','denied'])->default('denied');
The admin sees all items and I want a button next to each item called approve if the admin clicks it the status change from denied to approved, how can I create a function in the controller that changes only the status field? one besides the default edit and update function that is already working in my controller.
public function edit($itemid)
{
$where = array('itemid' => $itemid);
$data['item_info'] = Item::where($where)->first();
return view('items.edititem', $data);
}
public function update(Request $request, $itemid)
{
$request->validate([
'name' => 'required',
'description' => 'required',
'state' => 'required',
'price' => 'required',
'charityfee' => 'required',
'status' => 'required',
'category' => 'required',
]);
$update = [
'name' => $request->name, 'description' => $request->description,
'state' => $request->state, 'price' => $request->price,
'charityfee' => $request->charityfee, 'status' => $request->status,
'category' => $request->category, 'itemphoto' => $request->itemphoto
];
Item::where('itemid', $itemid)->update($update);
return Redirect::to('profile')
->with('success', 'Great! item updated successfully');
}
Although I tried this following code, an error appeared that the function I have called is not defined:(
public function editstatus($itemid)
{
Item::where('itemid', $itemid)->update(array('itemid' => 'available'));
}
function in controller
<td>approve</td>
the code in the view
Your problem is on editstatus function.
you want to update status => 'available' but you code update itemid => 'available'. that why it error.
you code should change to below:
public function editstatus($itemid)
{
Item::where('itemid', $itemid)->update(array('status' => 'available'));
}
I'm pretty sure your $where variable is wrong, You want to compare a variable with a field just get rid of the '=>'. You are basically doing an assigment operation and not a comparison.
You can have it this way
$data['item_info'] = Item::where($itemid, 'item_id')->first();
I am trying to check to see if (a) column(s) is/are unique by using the Rule::unique('table')->where(function($query) use($x) {...}); functionality but when I pass this into my validator I am getting a strange error. What I think is happening is that it is trying to check if a value is equal in the where the statement that I provided but also a column that it THINKS is the unique ID column for the table but it is not so it is breaking.
protected function validator(array $data)
{
$uid = 660000000;
$rule = Rule::unique('member_record')->where(function ($query) use ($uid) {
return $query->where('uniqueID', $uid);
});
return Validator::make($data, [
'fullName' => ['required', 'string', 'min:2'],
'member_id' => [
'bail', 'required', 'Numeric', $rule,
'exists:new_benefits_member,member_id'
],
'email' => ['bail', 'required', 'email', 'confirmed', 'unique:user,email'],
'password' => [
'required', 'string', 'min:8', 'confirmed',
'regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$/'
],
'terms' => ['required']
]);
}
However, then I am getting an error that looks like the following.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'member_id' in 'where clause' (SQL: select count(*) as aggregate from member_record where member_id = 660000000 and (uniqueID = 660000000))
What my only assumption is that when I am passing data into the Validator::make($data... it is trying to compare the $rule with the $data array and it is messing it up. Let me know if you have any fixes that I can try out.
The problem here is that the Rule::unique() function can take 2 parameters as shown below
public static function unique($table, $column = 'NULL')
{
return new Rules\Unique($table, $column);
}
if column is left as 'NULL' then this will default to the name of the key in the validator::make($x, [] <--- array
as shown in this example.
protected function validator(array $data)
{
$uid = 660000000;
$rule = Rule::unique('member_record')->where(function ($query) use ($uid) {
return $query->where('uniqueID', $uid)->orwhere('client_member_id', $uid);
});
$data['foo'] = 0;
$validator = Validator::make($data, [
'foo' => [$rule]
]);
return $validator;
}
results in this response
Column not found: 1054 Unknown column 'foo' in 'where clause' (SQL: select count(*) as aggregate from member_record where foo = 0 and (uniqueID = 660000000 or client_member_id = 660000000))
If you would like to exclude "is equal to" in the first part of the where clause you would perform a unique check like this
'member_id' => ['unique:member_record,foo']
If you would like to add additional where clauses then you would want to do something like this
'member_id' => ['unique:member_record,foo,NULL,id,bar,' . $uid]
This will return SQL looking like this
select count(*) as aggregate from member_record where foo = 660000000 and bar = 660000000
I am trying to update a blog post but I am getting unique key error from database part then I went without using model and directly accessing ORM but then again no success.
This is my routes spesific to edit
Route::get('/getedit/{slug}', array('as' => 'getedit', 'uses' => 'AdminController#getEdit'))->before('auth');
Route::post('/postedit', array('as' => 'postedit', 'uses' => 'AdminController#postEdit'))->before('auth');
Controller
public function getEdit($slug)
{
$article = Post::where('slug', '=' , $slug)
->firstOrFail();
return View::make('admin.edit', array(
'title' => $article->title,
'mainarticle' => $article->article,
'slug' => $article->slug,
'category' => $article->category
));
}
// Updates articles to database
public function postEdit()
{
$rules = [
'title' => 'required',
'article' => 'required',
'slug' => 'required|unique:posts,slug,9',
'category' => 'required'
];
$input = Input::all();
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
return Redirect::route('getedit')
->withErrors($validator);
// withInput not defined
}
else
{
$slug = $input['slug'];
/*$affectedRows = Post::where('slug', '=', $slug)->update([
'title' => $input['title'],
'article' => $input['article'],
'slug' => $input['slug'],
'category' => $input['category']
]);*/
/*$affectedRows = Post::where('slug', '=', $slug)->firstOrFail();
$affectedRows->title = $input['title'];
$affectedRows->article = $input['article'];
$affectedRows->slug = $input['slug'];
$affectedRows->category = $input['category'];
$affectedRows->save();*/
$post = DB::table('posts')->where('slug', '=', $slug)->update([
'title' => $input['title'],
'article' => $input['article'],
'slug' => $input['slug'],
'category' => $input['category']
]);
if ($post) {
return Redirect::route('dashboard')
->with('flash_message','Article Successfully Inserted');
}
else
{
return Redirect::route('dashboard')
->with('flash_message','Error updating data');
}
}
}
My model is just creating object of database (I am accidentally following fat controller and thin model approach as I am just trying the framework).
I have tried using Post::find(1)->update($data); method but that is returning unique violation and my current approach is just executing else statement which is triggered upon update failure.
Note: I am new to Laravel and trying this for the first time.
When you update a post, you'd rather send a POST (or better PATCH/PUT- http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) request to given resource.
That said, you would include edited row key in the url, and change your method to something like this:
// route
Route::post('/postedit/{id}', array('as' => 'postedit', 'uses' => 'AdminController#postEdit'))
->before('auth');
// controller
public function postEdit($id)
{
// if no posts with $id found, throws exception - catch it and eg. show 404
$post = Post::findOrFail($id);
$rules = [
'title' => 'required',
'article' => 'required',
'slug' => 'required|unique:posts,slug,'.$id, // to ignore this row in unique check
'category' => 'required'
];
// validate
$post->fill($input)->save(); // fill() in order to use mass-assignement check
// alternatively you can just update:
// $post->update($input);
// but then make sure $input has only elements corresponding to the table columns
Additionally, read about route grouping, so you don't need to add before('auth') to those routes separately.
You should check your database table indexes. You should make sure that only slug has unique index.
I see that you are checking unique for slug but you hardcoded 9 in the rule:
'slug' => 'required|unique:posts,slug,9',
It should be:
'slug' => 'required|unique:posts,slug,'.$id,
where $id id of post you try to edit.
You should include such id in your form as hidden element and not search records with slug that you have because it seems you can edit your slug and you may edit the wrong record or edit nothing.