Undefined property in Laravel using Eloquent - php

I have a problem when use Eloquent.
This is the error message.
Undefined property: Illuminate\Database\Eloquent\Collection::$refunds
This is My model.
class Beneficiary extends Eloquent {
public function refunds(){
return $this->hasMany('Refund');
}
}
class Refund extends Model {
protected $guarded = array();
public static $rules = array(
'request_id' => 'required',
'beneficiary_id' => 'required',
'concept' => 'required',
'date' => 'required | date_format:Y-m-d',
'amount' => 'required | min:-1 | numeric',
'deductible_amount' => 'required | numeric',
'max_applied' => 'required | numeric',
'yearly_balance' => 'required | numeric',
'payment_amount' => 'required | min:-1 | numeric',
'payment_date' => 'required | date_format:Y-m-d',
);
public function beneficiary(){
return $this->belongsTo('Beneficiary','beneficiary_id');
}
public function request(){
return $this->belongsTo('Models\Request','request_id');
}
}
And this is my Model.
class HomeController extends BaseController {
public function getIndex(){
$requests = Requisition::with(array(
'refunds' => function($refundsQuery){
$refundsQuery->with(array(
'beneficiary' => function($beneficiaryQuery){
$beneficiaryQuery->with(array('beneficiary', 'holder'));
}
));
},
'policy' => function($policyQuery){
$words=explode(' ',trim(Input::get('policy_code')));
$policyQuery->where('code','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$policyQuery->orWhere('code','LIKE','%'.$words[$i].'%');
}
},
'refunds' => function($refundsQuery){
$refundsQuery->with(array(
'beneficiary' => function($beneficiaryQuery){
$beneficiaryQuery->with(array('beneficiary','rut'));
}
));
}
));
if(Input::has('request_number')){
$words=explode(' ',trim(Input::get('request_number')));
$requests->where('number','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$requests->orWhere('number','LIKE','%'.$words[$i].'%');
}
}
if(Input::has('policy_code')){
$requests->whereHas('policy', function($policyQuery){
$words=explode(' ',trim(Input::get('policy_code')));
$policyQuery->where('code','LIKE','%'.$words[0].'%');
for($i=1;$i<count($words);$i++){
$policyQuery->orWhere('code','LIKE','%'.$words[$i].'%');
}
});
}
if(Input::has('rut')){
$person = Person::where('rut', Input::get('rut'))->get();
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->get();
$refunds = $beneficiary->refunds; //Error
}
$requests = $requests->paginate(10);
return View::make('home.index',array(
'requests'=>$requests,
'policy_code' => Input::get('policy_code'),
'request_number' => Input::get('request_number'),
'rut' => Input::get('rut')
));
In this line occurs the error $refunds = $beneficiary->refunds;
Any idea?

When you do
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->get();
Contains a Collection of models, not a Model, so you have to:
$beneficiaries = Beneficiary::where('rut',Input::get('rut'))->get();
foreach($beneficiaries as $beneficiary)
{
echo $beneficiary->refunds;
}
Or
$beneficiary = Beneficiary::where('rut',Input::get('rut'))->first();

Related

Undefined array key "id" in CodeIgniter 4

Undefined array key "id" in CodeIgniter 4
enter image description here
public function update($id)
{
$slug = url_title($this->request->getVar('nama_rak'), '-', true);
$this->rakModel->save([
'id' => $id,
'nama_rak' => $this->request->getVar('nama_rak'),
'slug' => $slug,
'detail_rak' => $this->request->getVar('detail_rak'),
'created_at' => $this->request->getVar('created_at'),
'updated_at' => $this->request->getVar('updated_at')
]);
return redirect()->to('/master/master_rak')->with('pesan', 'Data Berhasil diubah!');
}
this is the construct
class Master extends BaseController
{
protected $rakModel;
public function __construct()
{
$this->rakModel = new RakModel();
}
// Pengadaan Buku
public function master_rak()
{
$data = [
'pages' => 'Master Data',
'title' => 'Data Rak',
'rak' => $this->rakModel->getRak()
];
echo view("master/master_rak", $data);
}

laravel route resource update method

I'm work on create to-do app in laravel with JWt
all method (index,store,show ..etc) in route resource works well except update
in result its work well and get success response but its not change in database
** sorry my english is not good
this is my short codes
api.php
Route::middleware('jwt.auth')->group(function () {
Route::resource('/todo', 'API\TodoController');
});
BaseController.php
class BaseController extends Controller
{
public function sendResponse($result,$message)
{
$response=[
'success'=> true,
'date' => $result,
'message'=> $message
];
return response()->json($response,200);
}
public function sendError($error,$errorMessages=[],$code=404)
{
$response=[
'success'=> false,
'message'=> $error
];
if (!empty($errorMessages)) {
$response['date']=$errorMessages;
}
return response()->json($response,$code);
}}
TodoController.php
class TodoController extends BaseController
{
.
.
.
public function update(Request $request, Todolist $todolist)
{
//
$input = $request->all();
$validator = Validator::make($input, [
'title' => 'required | max:255',
'content' => 'required | max:255',
'status' => 'required | max:2',
'start_date' => 'required ',
'end_date' => 'required ',
]);
if ($validator->fails()) {
return $this->sendError('error validation', $validator->errors());
}
$todolist->title = $request->title;
$todolist->content = $request->content;
$todolist->status = $request->status;
$todolist->start_date = $request->start_date;
$todolist->end_date = $request->end_date;
$todolist->save();
return $this->sendResponse($todolist->toArray(), 'update successfully');
}}
this is results in postman
https://i.stack.imgur.com/4oHqC.png
You should refer Model before class
use App\Todolist;
class TodoController extends BaseController
{
.
.
.
public function update(Request $request, Todolist $todolist)
{
//
$input = $request->all();
$validator = Validator::make($input, [
'title' => 'required | max:255',
'content' => 'required | max:255',
'status' => 'required | max:2',
'start_date' => 'required ',
'end_date' => 'required ',
]);
if ($validator->fails()) {
return $this->sendError('error validation', $validator->errors());
}
$todolist->title = $request->title;
$todolist->content = $request->content;
$todolist->status = $request->status;
$todolist->start_date = $request->start_date;
$todolist->end_date = $request->end_date;
$todolist->save();
return $this->sendResponse($todolist->toArray(), 'update successfully');
}}
TodoList.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Todolist extends Model
{
//
protected $table='todolists';
protected $fillable =[
'title',
'content',
'status',
'photo_id',
'date_id',
'start_date',
'end_date',
'user_id'
];
}
todo table
https://i.stack.imgur.com/GGr5Q.png

LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

I'm supposed to display author details in bookformat method. But facing LogicException. Any suggestions thanks in advance. Im getting error like this LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation. Any help that would be great for me. If I comment authors in bookFormat() everything works fine. But Idk why I'm unable to get author details in my bookformat().
#booksController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Models\Book;
use App\Models\Author;
class BooksController extends Controller
{
public function index()
{
$books = Book::all();
$results = [];
foreach ($books as $book) {
$results [] = $this->bookFormat($book);
}
return $results;
}
public function bookFormat($book){
return [
'Id' => $book->id,
'Title' => $book->title,
'Author' => [
'Id' => $book->author->id,
'First_name' => $book->author->first_name,
'Last_name' => $book->author->last_name
],
'Price' => $book->price,
'ISBN' => $book->isbn,
'Language' => $book->language,
'Year' => $book->year_of_publisher
];
}
}
//book.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
public $timestamps = TRUE;
protected $table = 'books';
//rules
public static $rules = [
'title' => 'required|max:255',
'isbn' => 'required|max:50',
'author_id' => 'required|max:255',
'language' => 'required|max:255',
'price' => 'required|max:255',
'year_of_publisher' => 'required'
];
//relationship
public function author() {
$this->belongsTo(Author::class);
}
}
Instead of:
public function author() {
$this->belongsTo(Author::class);
}
you should have:
public function author() {
return $this->belongsTo(Author::class);
}
Notice the return difference.

Error Fatal error: Call to a member function insert() on a non-object

I'm using a callback after inserting in the database, to pass values to this other table, i think the method i used its fine. But it gives me this error when its inserting to the other table in the database, probably in my model, or something in the controller im kind of clueless in this error, can someone please help me.
Before someone say its to put $this->load->database(); its already in my autoload in config file :)
Fatal error: Call to a member function insert() on a non-object
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Finances::$inventory_model
Filename: controllers/finances.php
Line Number: 125
CONTROLLER:
public function inventory_management($post_array,$primary_key)
{
$this->load->model('inventory_model');
if($post_array['id_expense']!=null){
$type = 'add';
$id_exp_detail = $primary_key;
$result = $this->inventory_model->insert([
'id_exp_detail' => $id_exp_detail,
'name' => $post_array['brand'],
'quantity' => $post_array['item_quantity'],
'lote' => $post_array['package_code'];
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else if ($post_array['name']!=null){
$type = 'sub';
$id_treatment = $primary_key;
$result = $this->inventory_model->insert([
'id_treatment' => $id_treatment,
'name' => $post_array['name'],
'quantity' => $post_data['recomended_dose'],
'lote' => $post_array['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}else{
$type = 'sub';
$id_fertilization = $primary_key;
$result = $this->inventory_model->insert([
'id_fertilization' => $id_fertilization,
'name' => $post_data['name'],
'quantity' => $post_data['quantity'],
'lote' => $post_data['id_package'],
'type' => $type,
'date' => date(),
'id_user' => $this->session->userdata('id_user'),
'id_entity' => $this->session->userdata('id_entity')
]);
}
if($result){
echo "validation Complete";
}
}
MODEL
class CRUD_model extends CI_Model
{
protected $_table = null;
protected $_primary_key = null;
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
public function insert($data)
{
$this->db->insert($this->_table, $data);
// return $this->db->insert_id();
}
MODEL:
class inventory_model extends CRUD_model
{
protected $_table = 'inventory_management';
protected $_primary_key = 'id';
// ------------------------------------------------------------------------
public function __construct()
{
parent::__construct();
}
// ------------------------------------------------------------------------
}
here is the wrong you call wrong model file
$this->load->model('inventory_model');
it should be
$this->load->model('crud_model');
and you use wrong way to pass array in function
$param = array('id_exp_detail' => $id_exp_detail, 'name' => $post_array['brand'], 'quantity' => $post_array['item_quantity'], 'lote' => $post_array['package_code'], 'type' => $type, 'date' => date(), 'id_user' => $this->session->userdata('id_user'), 'id_entity' => $this->session->userdata('id_entity'));
$result = $this->inventory_model->insert($param);

Unit Testing REST Update with Laravel and Mockery

I can't seem to figure out how I unit test the update of my controller. i'm getting the following error:
method update() from Mockery_0_App.... Should be called exactly 1 times but called 0 times.
After I remove the if statement in the update (after checking if the allergy exists), I get the following error on the line where I add the id the the unique validation rule:
Trying to get property of on object
My Code:
Controller:
class AllergyController extends \App\Controllers\BaseController
{
public function __construct(IAllergyRepository $allergy){
$this->allergy = $allergy;
}
...other methods (index,show,destroy) ...
public function update($id)
{
$allergy = $this->allergy->find($id);
//if ($allergy != null) {
//define validation rules
$rules = array(
'name' => Config::get('Patient::validation.allergy.edit.name') . $allergy->name
);
//execute validation rules
$validator = Validator::make(Input::all(), $rules);
$validator->setAttributeNames(Config::get('Patient::validation.allergy.messages'));
if ($validator->fails()) {
return Response::json(array('status' => false, 'data' => $validator->messages()));
} else {
$allergy = $this->allergy->update($allergy, Input::all());
if ($allergy) {
return Response::json(array('status' => true, 'data' => $allergy));
} else {
$messages = new \Illuminate\Support\MessageBag;
$messages->add('error', 'Create failed! Please contact the site administrator or try again!');
return Response::json(array('status' => false, 'data' => $messages));
}
}
//}
$messages = new \Illuminate\Support\MessageBag;
$messages->add('error', 'Cannot update the allergy!');
return Response::json(array('status' => false, 'data' => $messages));
}
}
TestCase:
class AllergyControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
$this->allergy = $this->mock('App\Modules\Patient\Repositories\IAllergyRepository');
}
public function mock($class)
{
$mock = Mockery::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function tearDown()
{
parent::tearDown();
Mockery::close();
}
public function testIndex()
{
$this->allergy->shouldReceive('all')->once();
$this->call('GET', 'api/allergy');
$this->assertResponseOk();
}
...Other tests for Index and Show ...
public function testUpdate()
{
$validator = Mockery::mock('stdClass');
Validator::swap($validator);
$input = array('name' => 'bar');
$this->allergy->shouldReceive('find')->with(1)->once();
$validator->shouldReceive('make')->once()->andReturn($validator);
$validator->shouldReceive('setAttributeNames')->once();
$validator->shouldReceive('fails')->once()->andReturn(false);;
$this->allergy->shouldReceive('update')->once();
$this->call('PUT', 'api/allergy/1', $input);
$this->assertResponseOk();
}
}
Config validation rules file:
return array(
'allergy' => array(
'add' => array(
'name' => 'required|unique:Allergy'
),
'edit' => array(
'name' => 'required|unique:Allergy,name,'
),
'messages' => array(
'name' => 'Name'
)
)
);
Is there a way to actually mock the value provided into the validation rule? Or what is the best way to solve this?
I changed my code to this and now it works! :)
$validator = Mockery::mock('stdClass');
Validator::swap($validator);
$allergyObj = Mockery::mock('stdClass');
$allergyObj->name = 1;
$input = array('name' => 'bar');
$this->allergyRepo->shouldReceive('find')->with(1)->once()->andReturn($allergyObj);
$validator->shouldReceive('make')->once()->andReturn($validator);
$validator->shouldReceive('setAttributeNames')->once();
$validator->shouldReceive('fails')->once()->andReturn(false);;
$this->allergyRepo->shouldReceive('update')->once();
$this->call('PUT', 'api/allergy/1', $input);
$this->assertResponseOk();

Categories