Not getting the id in where clause - Laravel 5.2 - php

I need to get the record with special id and i have this in my method :
public function addedMark()
{
$user = Auth::user();
$subject = ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id');
return view('educator.account.marks', [
'user' => $user,
'marks' => StudentMark::where('subject_id', $subject)->get()
]);
}
When i do dd(ClassSubject::where('teacher_id', $user->id)->pluck('id','subject_id')); i see that I'm getting the information that i need, but when i do dd(StudentMark::where('subject_id', $subject)->get()); it returns an empty array.
Any idea why?

Change it to (whereIn)
'marks' => StudentMark::whereIn('subject_id', $subject)->get()
and let see what hapens

In $subjectyou have id and subject_id. You might wanna just take subject_id.
So change this: StudentMark::where('subject_id', $subject)->get()
to
StudentMark::where('subject_id', $subject[1])->get()

Related

Eloquent update all column fields

I want to update all the tables in the Article migration to a specific Boolean value which is set by the user.
I have written this code:
public function changeComVote() {
$data = request()->validate([
'status' => 'required'
]);
Article::query()->update(['isOnly' => $data['status']]);
event(new changesMade);
}
Although $data['status'] doesn't get passed inside the query and nothing happens, when i set it manually it works like a charm, what could be the problem?
Using $data['status'] from request will give you a string as a result, not a boolean.
Try this way
Article::query()->update(['isOnly' => $data['status'] == 'true']);
You can delete that "query()" thing and use this instead
Article::update(['isOnly' => $data['status']]);
or
Article::update(['isOnly' => ($data['status']] === "true"));
You can also specify where the row by using id
Article::find($id)->update(['isOnly' => ($data['status']] === "true"));

laravel many to many relation sync "Illegal offset type"

I am new to larvel 5.6 and trying to learn it.
I have the following code:
$gr = group::create([
'book_id' => $book_id,
]);
$owner = Book::where('id', $book_id)->pluck('user_id');
$id1 = Auth::user()->id;
$gr->users()->sync([$id1 => ['last_seen_id' => -1], $owner => ['last_seen_id' => -1]]);
in the pivot table group_user I have one extra column which is last_seen_id but I get the error :
"Illegal offset type"
so what I tried is to change the code to the following:
$gr = group::create([
'book_id' => $book_id,
]);
$owner = Book::where('id', $book_id)->pluck('user_id');
$gr->users()->sync([Auth::user()->id => ['last_seen_id' => -1], $owner => ['last_seen_id' => -1]]);
But I keep getting the same error, please kindly help me to understand what is wrong and how to solve it.
In your code, the $owner represent the object, and by you're code, it looks like you're trying to get it to be an array, both types cannot be used as an array index, which you have in your last line.
Maybe you're trying to get only one owner id, so what I'm guessing you need to get is
$owner = Book::where('id', $book_id)->first();
if(!empty($owner)) {
$owner = $owner->user_id;
} else {
throw new \Exception();
}

Is there a way to check if a couple of inputs are unique in laravel 5.2?

update
What I have is a table with these columns:
- ID
- production_year
- type
If the type is already present in the table with the value the user wants to pass, check if production_year is already present too, but fail the validation ONLY if these values are present in the same record. Otherwise let the user to store this record.
I'm trying to check the uniqueness of a couple of fields in the same record...
I've seen the documentation about the conditional validation, but I didn't quite find the answer there.
the code
public function rules()
{
return [
// I'd like to check the uniqueness of both of them. In the same record
'production_y' => 'required|unique',
'fk_type' => 'required|unique',
];
}
Any idea? Thanks!
Laravel 5.3 Update:
Now, you can generate the same rule fluently using the Rule (\Illuminate\Validation\Rule) class.
NULL,id part of the string way is no more required. See:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => [
'required',
Rule::unique('your_table', 'production_year')->where(function($query) {
$query->where('type', $type);
}),
],
];
}
Original Answer
Can't test right now, can you try:
public function rules()
{
$type = $this->get('fk_type');
return [
'production_y' => "required|unique:your_table,production_year,NULL,id,type,{$type}",
// ...
];
}
Explaination:
unique:your_table Set the table for the unique check.
,production_year This matches with production_y.
,NULL,id check all the records.
3.1. if you use like {$id},id it will check uniqueness except the record with the {$id},
,type,{$type} and the type should be {$type}
That will produce sth. like (not exact query, just to express the idea):
select count(*) from your_table where production_year = $product_y and where type = $type and where id <> null
if someone cames from laravel 8, i tried this and it worked !!
for me i need to check the uniqueness of (category_id,subcategory_id) which mean you can find (1,2),(1,3),(2,1),(2,3) but you cant find similar couple !!
'category' => "required|unique:tickets,category_id,NULL,id,subcategory_id,{$request->input('subcategory')}"

Update only one field on Cakephp 3

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));
}

Laravel - Saving data to many-to-many relationship

is it possible to save more data than just the id's to a many-to-many pivot?
My Code:
public function lists() {
return $this->belongsToMany('ShoppingList','shopping_list_ingredients','shopping_list_id','ingredients_id')
->withPivot(array('unit','amount'))
->withTimestamps();
}
and vice verca!
And now, I need to add the additional data to the pivot.
This is my saving code:
$list = new ShoppingList;
$list->user_id = Auth::user()->id;
$list->title = Input::get('recipe_title');
$list->save();
$list->ingredients()->sync(Input::get('ingredient'));
$list->push();
and my view code:
- {{$i->amount}} {{$i->unit}} {{$i->name}} - {{ Form::checkbox('ingredient[]', $i->id) }}<br/>
Now I need somehow pass the "amount" and "unit" for each ID into the controller and into the pivot. Right now, it only saves the IDs.
How can I do it?
You have to use the attach function.
$list->ingredients()->attach($ingredients->id,['unit' => $unit, 'amount' => $amount]);
You may try something like this:
$ingredientId = Input::get('ingredient');
$amount = 'some amount';
$unit = 'some unit';
$pivotData = array($ingredientId => array('amount' => $amount, 'unit' => $unit));
$list->ingredients()->sync($pivotData);
You may also use attach method, read the documentation on Laravel Website for more information.

Categories