problem with relation hasmany laravel proprty retro - php

I have a relation hasMany but it doesn't work at my controller
code season model :
public function retro () {
return $this->hasMany('App\Models\Retrocession','season_id');
}
code controller :
$hotelagencie = HotelAgency::find($id) ;
$hotel = $hotelagencie->hotel;
$season = $hotel->seasons;
return $season->retro
Ereur : Property [retro] does not exist on this collection instance.
Thxyou .

We confirmed what you want(Select all the retro from all the seasons), so I think I can give you an answer:
This is what you got:
$hotelagencie = HotelAgency::find($id) ;
$hotel = $hotelagencie->hotel;
$season = $hotel->seasons;
return $season->retro
This is what I think it needs to be:
$hotelagencie = HotelAgency::find($id) ;
$hotel = $hotelagencie->hotel;
$seasons = $hotel->seasons;
return $seasons->pluck('retro');
For more info on what pluck() is and how to use it, please refer to the official docs:
https://laravel.com/docs/6.x/collections#method-pluck
I hope it helps ;)

Related

setrelation method doesn't work in laravel

My user relationship is :
public function country()
{
return $this->belongsTo(Country::class);
}
and the query is :
$user = User::with('country')->first();
I want to check if the country is empty replace that with a default data or anything
so first I tried like this :
if(empty($user->country)){
$user->country = "some default value";
}
and It didn't work after searching I try this :
if(empty($user->country)){
$user->setRelation('country' , 'some default value');
}
and again it doesn't work for me. the "setRelation" remove the country key in the user's object
If empty / null received in eloquent result relation key, then set defaultOject can be set as follows:
For single relation:
$modelInstance = $modelInstance->setRelation('relationName', $relationModelObject)
For multiple relation:
$modelInstance = $modelInstance->setRelation('relationName', collect([$relationModelObject]))
Multiple relation example:
$defaultMedia = new Media;
$defaultMedia->id = 0;
$defaultMedia->file_name = 'defaultImage.jpg';
$result = Post::with('media')->get();
$result->transform(function ($post, $key) use($defaultMedia) {
if($post->media->count() == 0) {
$post->setRelation('media', collect([$defaultMedia]));
}
return $post;
});
return $result;
Now, in final $result you shall get $defaultMedia when relation returned null.
It does not work that way because country is not a direct attribute/column of the user.
You can change your code like this.
if(empty($user->country)){
$user->country->update([
'name' => "some default value"
]);
}
Hope it works. :-)

Passing data between 2 models in 1 controller function laravel

I need to get the lecture id in my student table and from then only can i get the lecture's data using that id. The problem is, the $lectureID is null when i try to apply it on the lecture model, but when i check on the console, it does get the data. Thanks in advance.
Controller
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
return $lectureDATA;
}
you can try two ways
public function getLecture($id)
{
## way 1
$lectureID = student::where('student_id',$id)->value('lecture_id_FK');
$lectureDATA = lecture::where('lecture_id',$lectureID)->first();
## way 2
$lectureID = student::where('student_id',$id)->first();
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
before check what inside $lectureID:
public function getLecture($id)
{
$lectureID = student::select('lecture_id_FK')->where('student_id',$id)->first();
dd($lectureID);//I believe inside will be object with lecture_id_FK
//then just
$lectureDATA = lecture::where('lecture_id',$lectureID->lecture_id_FK)->first();
return $lectureDATA;
}
Recommended way to do it:
In Student model class ( recommend use capital S )
class student
{
public function lecture(){
return $this->hasOne('App\lecture','lecture_id_FK','lecture_id');
}
}
then just load studen with lecture like this
$student = studend::with('lecture')->find($id);
$lecture = $student->lecture;

How to test Laravel Scout (with Algolia)?

I have a piece of code like this:
public function index(Request $request, Runner $runnerParam)
{
$name = $request->input('name');
$fromDate = $request->input('from_date');
$toDate = $request->input('to_date');
$runners = Runner::query();
if ($name) {
$runners = $runnerParam::search($name);
}
if ($fromDate && $toDate) {
$runners->where('created_at', '<=',$toDate )
->where('created_at', '>=', $fromDate);
}
switch ($type) {
case 1:
$runners->where('role', '=', runner::PRO);
break;
case 2:
$runners->where('role', '=', runner::AMATEUR);
break;
}
$runners = $runners->get();
foreach($runners as $runner){
$runner->distance = $runner->stats->sum('distance');
}
return $runners;
}
The question is, how do I write test for this? If I just try to provide 'name' in test, it will return nothing like search() function isn't working at all while testing. Tried really hard to find anything on this, but the info is scarce and I only ended up with something like 'set Algolia driver to null', which I managed to do, but to no effect since I don't know what's the point of doing so and how do you apply it in tests. There are absolutely no examples of successful tests out there, just a few questions with short answer that didn't quite help.
A piece of test:
public function testNameFilter()
{
$this->logIn();
$runners = factory(runner::class, 30)->create();
$name = $runners[0]->name;
$response = $this->json('get', route('api::runners.get'), ['name' => $name]);
$responseContent = $response->getContent();
...
}
So, what I get in the end is empty responseContent, which means this is not the right way to test this. Any thoughts?
Why not just test that you've properly configured your class to use Laravel Scout, vs. testing that Laravel Scout works as expected?
public function class_uses_scout()
{
$this->assertTrue(in_array('Laravel\Scout\Searchable', class_uses('App\FooModel')));
}
public function class_has_searchable_array()
{
// compare the searchable array with a hardcoded array here
}
Be sure to set your disable Laravel Scout in your test environment.

How to save update from relationships model Laravel 5.3

I want to save an update from One to Many relation model in Laravel 5.3, but I have this error.
FatalThrowableError in HasOneOrMany.php line 221:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\wismasejahtera\app\Http\Controllers\JurnalController.php on line 129
Here is my Jurnals model:
public function djurnals()
{
return $this->hasMany('App\DJurnals', 'jurnal_id');
}
And here is my Djurnals model:
public function jurnals()
{
return $this->belongsTo('App\Jurnals');
}
public function rekenings()
{
return $this->belongsTo('App\Rekenings');
}
And here is my Controller:
$jurnal = Jurnals::find($id);
$jurnal->no_jurnal = $request->no_jurnal;
$jurnal->tgl_jurnal = $tglJurnalFix;
$jurnal->keterangan = $request->keterangan;
$jurnal->save();
//ini Array
$kode_rekening = $request->kode_rekening;
for($i=0; $i<count($kode_rekening); $i++){
$djurnal = Djurnals::where('jurnal_id', $id)->get();
$djurnal->kode_rekening = $request->kode_rekening[$i];
$djurnal->keterangan_rekening = $request->keterangan_rekening[$i];
$djurnal->d_k = $request->d_k[$i];
$djurnal->jumlah = $request->jumlah[$i];
if($request->d_k[$i] == 'D'){
$saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
->increment('saldo', $request->jumlah[$i]);
}
else{
$saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
->decrement('saldo', $request->jumlah[$i]);
}
$jurnal->djurnals()->save($djurnal);
}
return Redirect::to('jurnal');
And the error is in this row in Controller:
$jurnal->djurnals()->save($djurnal);
When I use this way to save a new jurnal and djurnal, it works correctly. But, When I try to save an update, it show an error. How can I save this update data to database? Anyone can help me?
Since you use the jurnal_id to get the Djurnals model, you need to save it directly.
Replace
Djurnals::where('jurnal_id', $id)->get();
With
Djurnals::where('jurnal_id', $id)->first();
Replace
$jurnal->djurnals()->save($djurnal);
With
$djurnal->save();
$jurnal->djurnals()->save($djurnal); Should be used only when saving a newly created model.

Laravel Eloquent Save Item

When I try to save an item in Laravel it says the following.
Call to undefined method Illuminate\Database\Query\Builder::save()
I have followed the documentation, and i can delete items fine just not update. Is there anything wrong with my code?
public function publishedMain($id, $state){
$userId = Auth::user()->id;
$userAdmin = Auth::user()->admin;
if($userAdmin == "0"){
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state));
$clients->active = $state;
$clients->save();
die('not admin');
}else{
$clients = Clients::whereRaw('id = ?', array($id));
$clients->active = $state;
$clients->save();
die('admin');
}
}
Many Thanks
Brent
You call the save() method on the query builder, not on your model.
You're missing the ->first() piece:
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state))->first();
Of course, this will get the first client, so naming the variable $clients makes not much sense.
You shall also check if your $clients variable is not null, in which case it didn't find anything.
(btw, your model should be called Client, not Clients)

Categories