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.
Related
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.
I am having a hard time with Laravel. I have a query that returns all the table columns. The problem is that a field "foto" returns as an empty string in the JSON when I use the "get" or "find" methods. Paginate it works as expected.
This query:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->paginate(50);
foto comes as:
"foto": "data/image:93483940349"
Now, with this:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->find(1);
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->get(50);
foto comes as:
"foto" : ""
I am returning the data from the controller like this:
return response()->json($resultado, 200);
In my operador model I have the following mutator:
public function getFotoAttribute($value)
{
if ($value != null)
{
return pg_escape_string(fgets($value));
}
return null;
}
Try updating your mutator like this:
public function getFotoAttribute()
{
if ($this->attributes['foto'] != null)
{
return pg_escape_string(fgets($this->attributes['foto']));
}
return null;
}
After fighting 2 hours, I give up. As a workoaround I used this to replace the find method.
$resultado = $query->where('id_admin', '=', $id_admin)->with('telasPermissao.itemPermissao')->where('id', 517 )->paginate(1)
If someone knows what happened please post an answer.
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 get from all of my records the value of the filename fields but i have this error. Can anyone help me?
My Code:
$acao = Acao::where('estado_id', '1');
if($acao->count() >= 1) {
$filename = $acao->imagem;
$path = asset('images/acoes/'.$filename);
return view ('CFAE.index', compact('path'))->withAcoes($acao);
}else{
return view ('CFAE.index')->withAcoes($acao);
}
And the laravel show me this error:
Undefined property: Illuminate\Database\Eloquent\Builder::$imagem
You should use the first() method to get an object:
$acao = Acao::where('estado_id', '1')->first();
You do not use it, so you get an instance of Query Builder which doesn't have imagem property.
Also, to check if object is found or not, do this:
if (!is_null($acao)) {
When you do
$acao = Acao::where('estado_id', '1')->get();
you get collection of models not model so you need to do
foreach($acao as $val)
{
$val->imagem
}
or you could use
$acao = Acao::where('estado_id', '1')->first();
I an developing a page to create, update, delete and view an event in which there is error while updating the event. There is a event table and a event_collection table. In that event_collection table there is event_id which is id of an event and a collection_id which is from other table collection.
When i create an event, all the data gets stored in event table except the collection one. in the collection table data gets stored in one by one manner like if I check 2 items in collection, it will generate 2 ids with same event_id and 2 collection_ids.
There is problem in update, when i try to update the code, it gives me error as
BadMethodCallException in Macroable.php line 81:
Method update does not exist.
Update method is:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
$checkbox_selection = Input::get('agree');
$choosen_checkbox = $id;
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
// return $collection_event;
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
// $collection_id = $id;
foreach($collection_event as $k){
// return $k;
if($k->event_id == $choosen_checkbox){
$data = $request->all();
$data['event_id']= $choosen_checkbox;
$data['collection_id'] = $collection;
$collection_event->update($data);
}
}
}
}
My store method is:
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
// return $checkbox_collection;
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
$event_id = $query->id;
$pro_id = $query->provider_org_id;
/*For the checkbox selection, if they are multiple store each separately*/
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
$collection_id = $query->id;
if($collection_id){
$data = $request->all();
$data['event_id']= $collection_id;
$data['collection_id'] = $collection;
$create_collection = EventCollection::create($data);
}
}
}
return view('event.pic_upload',compact('event_id','pro_id'));
}
Store method works properly! Can someone please tell any solution? I am badly stucked in this.
I do not think the 'update' method works on collections.
This line will return a collection
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
You do not want a collection, rather a query. As given in the docs:
`App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);`
Try removing the '->get()' from the statement.