eloquent distinct select laravel - laravel

I want to show the company list with distinct is there's a way using eloquent? this code isn't working
public function create()
{
$goods = goods::all();
$company = company::all()->distinct('name')->get();
return view('pages.purchaseCreate',['goods' => $goods, 'company' =>$company]);
}
this are the error message
Method Illuminate\Database\Eloquent\Collection::distinct does not exist.

That's because all() returns a collection. This should work:
$company = company::distinct('name')->get();

Related

How can I get a query with a conditional in a third relation?

Im using Laravel 7 and to get an array like this Array image spect result
And im working with Eloquent. This is my code for that array
**return EvaluateTeacherQuestion::with('evaluate_teacher_possibles_answers')->get();**
And this is my function evaluate_teacher_possibles_answers to make the relationship
public function evaluate_teacher_possibles_answers()
{
return $this->hasMany(EvaluateTeacherPossibilites::class)->withCount('evaluate_teacher_answers')->with('evaluate_teacher_answers');
}
And to get the third condition use this
public function evaluate_teacher_answers()
{
return $this->hasMany(EvaluateTeacherAnswer::class, 'evaluate_teacher_possible_id');
}
The problem is in the table evaluate_teacher_answers, I need get only this that if a condition (teacher_id = $teacher) is right.
When you add the whereHas condition a subquery is added.
Eg:
EvaluateTeacherQuestion::with('evaluate_teacher_possibles_answers')->whereHas('evaluate_teacher_possibles_answers',function($query){
$query->where('column','operation','value');
})->get();
With this way, will included relation in model and will execute conditions on closure from related model
Try this way:
remove with('evaluate_teacher_answers') from evaluate_teacher_possibles_answers relation:
public function evaluate_teacher_possibles_answers()
{
return $this->hasMany(EvaluateTeacherPossibilities::class)->withCount('evaluate_teacher_answers')->;
}
then load that relation with your condition:
$value = EvaluateTeacherQuestion::with(['evaluate_teacher_possibles_answers'=>function($query)use($teacher_id)
{
$query->with(['evaluate_teacher_answers'=>function($query)use($teacher_id){
$query = $query->where('evaluate_teacher_answers.teacher_id',$teacher_id);
}]);
}])->get();

How can I use laravel db query ->update() method in if statement

I want to check something in if, and if that condition is true I want to update the record that was fetched before.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (this condition will pass I want to update this record) {
$resultQuery->update(array('price_usd' => $card->prices->usd));
}
When I use the ->update() like this, I get an error:
Call to undefined method stdClass::update();
How can I do this ?
The first() function on laravel query builder returns a stdClass meaning Standard Class.
There is no function called update() in stdClass in php. You have called update() on stdClass, and that causes the error.
There are several ways to achieve your goal.
Use Laravel query builder update() function.
$resultQuery = DB::table('cards')->where('api_id', $card->id)->first();
if (your_condition) {
Db::table('cards')
->where('api_id', $card->id)
->update([
'price_usd' => $card->prices->usd
]);
}
If you don't want to fetch the card data, don't call first()
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if (your_condition) {
$resultQuery
->update([
'price_usd' => $card->prices->usd
]);
}
Use Eloquent models (Laravel's preferred way)
Create an Eloquent model for Cards (if you have not done already).
public class Card extends Model
{
}
Use eloquent query builder to fetch data. And use model update() function to update data.
$resultingCard = Card::where('api_id', $card->id)->first();
if (your_condition) {
$resultingCard->update([
'price_usd' => $card->prices->usd,
]);
}
If you're using model
You can add in card controller
$card = Card::where('api_id', $card->id)->first();
if (someConditional)
{
// Use card properties, number is a example.
$card->number = 10
// This line update this card.
$card->save();
}
You can learn more about eloquent here.
Something like this:
$resultQuery = DB::table('cards')->where('api_id', $card->id);
if ($resultQuery->count()) {
$object = $resultQuery->first();
$object->price_usd = $card->prices->usd;
$object->save();
}
Or look for an alternative solutions here: Eloquent ->first() if ->exists()

Error : Method Illuminate\Database\Eloquent\Collection::StudentInfo does not exist. (Laravel 5.6)

I am new to make join tables with Eloquent. I want to join 3 tables. But it shows me error. What's my mistake, if anyone notice it will be helpful for me. Here is tables....
In 1st table Applications(id,u_id,program_name) 2nd table StudentInfos(id,u_id,.....) 3rd table users(id,.....)
in Application model
public function StudentInfo()
{
return $this->hasOne('App\StudentInfo', 'u_id', 'u_id');
}
in StudentInfo model
public function User()
{
return $this->hasOne('App\user', 'u_id', 'id');
}
From controller
public function view_application($id)
{
$vu_data = Application::where('id', $id)->get();
$vu_data2 = $vu_data->StudentInfo()->get();
return $vu_data2;
}
$vu_data2 = $vu_data->StudentInfo()->get();
is returning a collection and not just a single Application Model. Change "get()" to "first()", and this will fix your first error. So change:
$vu_data = Application::where('id', $id)->get();
to
$vu_data = Application::where('id', $id)->first();
When you do get(), it returns a collection. You can do :
$vu_data = Application::findOrFail($id);
$student = $vu_data->StudentInfo;
$user = $student->User;

Laravel firstOrCreate without Eloquent

Eloquent has a firstOrCreate method which gets a model based on a condition, or creates it if it doesn't exist.
Is there any equivalent method in Laravel's query builder (i.e. NOT in Eloquent)? For example:
$row = DB::table('users')->where('user_id', 5)->firstOrCreate('name' => 'Peter', 'last_name' => 'Pan');
That would try to get a row from users with 'user_id'==5. If it doesn't exist, it would insert a row with that id number, plus the other mentioned fields.
EDIT: I'm not trying to apply my question with users. I used users as an example to make as clear as possible what I'm looking for.
updateOrInsert function with empty values give me the result like firstOrCreate
Nope, Laravel firstOrCreate is function, that says next:
public function firstOrCreate(array $attributes, array $values = [])
{
if (! is_null($instance = $this->where($attributes)->first())) {
return $instance;
}
return tap($this->newModelInstance($attributes + $values), function ($instance) {
$instance->save();
});
}
But you can add it with query micro:
DB::query()->macro('firstOrCreate', function (array $attributes, array $values = [])
{
if ($record = $this->first()) {
// return model instance
}
// create model instance
});
So than you will be able to call it same way you do with Eloquent.
$record= DB::table('records')->where('alias', $alias)->firstOrFail();
Yeah of course! Just use normal SQL and ->selectRaw( your conditions ) and look for if there is a entry where your specifications are.
https://laravel.com/docs/5.7/queries#raw-expressions

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

Resources