I'm trying to show a title based on whether a specific column in my table is 1 or 0. In my Controller I have (edited out some irrelevant code):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
and in my view:
#if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
#endif
However I get error message
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
Ive tried the following but I get errors every time:
#if($vegan[0]->vegan == 1)
This gives undefined offset errors
The problem is you're missing first() after your queries:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
In this line, you're injecting a Company into your show method via URL parameter:
public function show(Company $id){ ... }
At that point, $id is either a Company instance or null. Calling $vegan = Company::find($id) doesn't make any sense, and I'm actually surprised you don't get an error at that point in the code.
Also, if you're using injection, name the variable correctly Company $company to avoid confusion, and reference later:
public function show(Company $company){
$vegan = $company;
$vegetarian = $company;
// Or `$vegan = Company::find($company->id);`
// (This is redundant, but demonstrates the syntax)
return view("...")->with(...);
}
Alternatively, remove injection and query:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
Either way, find() does not return a Collection, so $vegan->vegan would not return "Property [vegan] does not exist on this collection instance.", but something about your usage is treating it that way.
Related
Im having an issue using CI4
I kept on getting error "Call to a member function get_courses() on null" even though this function exist on my model. Here's how I code it.
courseModel.php
public function get_courses() //get courses under the teacher
{
$builder = $this->db->table('tbl_course_access');
$builder->select('*');
// $builder->where('user_id', $userid);
// $builder->where('school_id', $schoolid);
//$builder->groupBy('course_id');
$query = $builder->get();
$results = $query->getResult();
return $results;
}
and on my controller I call it like this
Dashboard.php
$temp = $this->courseModel->get_courses();
var_dump($temp);
exit;
note that I called the model properly base on the CI manual
$this->courseModel = model('App\Models\CoursetModel', false);
What did I do wrong or any configuration I need to do on CI4?
My bad, I had typos on my codes that makes the error! Must be a headache doing all the work!
I have problem with my code in Laravel Framework. What I am trying to do is sell method inside model. The problem is that $variable keeps its value untill next code execution. How I should make it so it's gonna work like I want to?
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.
Even if you have deleted a record from a database by $this->delete(), $user_item variable still holds a reference to the filled model until the script ends or you destroy the variable.
It seems that you want to return a result of the sell() function. In your case it would be
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->Sell();
I don't know what you are trying to do but below code will solve your issue -
/// Model method.
public function Sell()
{
$this->UserData->increment('gold', ($this->ItemData->price / 100) * 80);
$this->delete();
$this->ItemData = $this->ItemData->fresh()
return null;
}
///in controller
$user = \Auth::user();
$user_item = UserItems::find(10);
$user_item->Sell();
return $user_item->ItemData->name; /// Returns full data about model even if I deleted it/sold. After next refresh, returns null/error.I want it to return null since beginning.
I'm trying to pass id from query from one database table to another table to which is related.
But, since they are related I have to pass it as instance of the entity(class) to which is related.
This is error I got:
Argument 1 passed to App\Entity\KeywordRating::setKeywordId() must be an instance of App\Entity\Keywords, integer given, called in C:\xampp\htdocs\ratingAPI\src\Service\KeywordRatingService.php on line 26
This is my code:
public function insertRating($params, ObjectManager $manager, KeywordsRepository $keyRep, ProvidersRepository $provRep)
{
$keywordId = $keyRep->checkKeyword(strtolower($params['keyword']))->getId();
$providerId = $provRep->checkProvider($params['provider'])->getId();
$rating = new KeywordRating();
$rating->setKeywordId(<Keywords instance> $keywordId);
$rating->setProviderId(<Providers instance> $providerId);
if($params['attr'] === 'rocks')
{
$rating->setRocksRating($params['rating']);
$rating->setSucksRating(0);
} else
{
$rating->setRocksRating(0);
$rating->setSucksRating($params['rating']);
}
$rating->setRocksVotes(10);
$rating->setSucksVotes(8);
$rating->setSumVotes(18);
$rating->setScore(2.50);
$manager->persist($rating);
$manager->flush();
}
This is sql query:
public function checkKeyword($keyword)
{
return $this->createQueryBuilder('k')
->where('k.keyword_name = :val')
->setParameter('val', $keyword)
->getQuery()
->getOneOrNullResult();
}
checkProvider() is the same, only different parameters.
How do I do that?
Assuming you have a namespace called Entities where you have all your entities classes, you can try something like this:
$entityManager = $this->getDoctrine()->getManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('keyword')
->from('App\Entity\Keywords', 'keyword')
->where($queryBuilder->expr()->eq('keyword.keyword_name', $queryBuilder->expr()->literal($keyword)));
$result = $queryBuilder->getQuery()-> getOneOrNullResult();
return $result;
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.
I need to return email of the user like in example:
public function getUserEmailAttribute()
{
$user = User::find($this->used_by);
return $user->email;
}
When I use $this->used_by it's throw me this error:
Trying to get property of non-object (View: /home/mertindervish/Documents/school/app/views/admin/invitation/list.blade.php)
But when I use a string like '2', '3' it's working. Is there any problem with my code? I tried to var_dump $this->used_by and it's return string(1).
It turns out that one invitation didn't have a valid used_by value.
To prevent such an error in the future, add a null check:
public function getUserEmailAttribute()
{
$user = User::find($this->used_by);
if(is_null($user)) return null;
return $user->email;
}