getting the value of the single field output using the codeigniter active record - codeigniter

the following function is supposed to read the name of the given asset code from the database. but it triggers the error: "Trying to get property of non-object"
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
return $this->db->get()->result()->row('name');
}
All I want is to have the name of the asset returned back to the controller! Your help is highly appreciated!

Use row() like,
return $this->db->get()->row()->name;

Use row() for a single row, and result() for multiple rows.

do like this, asset_types is your table name
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
return $this->db->get('asset_types');
}
And in your controller acess it like
$result=$this->modelname->sban_name('$asset')->row();
$name=$result->name;

I think it's important to check if the record that satisfies the conditions even exists in the database. Code for the model:
function sban_name($asset){
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code',$asset);
$row = $this->db->get()->row();
if (isset($row)) {
return $row->name;
} else {
return false;
}
}
Simply call the function from the controller like so:
$response = $this->model_name->sban_name($asset)

Try this code of block , I already checked and works fine:
function sban_name($asset)
{
$this->db->select('name');
$this->db->from('asset_types');
$this->db->where('code', $asset);
return $this->db->get()->row()->name;
}

Related

Get Id Field From Eloquent Laravel

I want get id value from eloquent laravel and passing to variable to insert process. this is my eloquent to get data from siswa table
$siswa = Siswa::where('nis', $row['nis'])->first();
but when accessing id value like $siswa->id I'm getting error
enter image description here
Use this code
if($siswa){
$id=$siswa->id;
}
$siswa variable can be null. Look at its contents with the dd($siswa) command.
To escape the error you can use it like this:
if($siswa)
{
// $siswa not null.
}
You have two ways to fix this.
1/ You can use ->firstOrFail() to display a 404 page in case of your data is not found :
$siswa = Siswa::where('nis', $row['nis'])->firstOrFail();
// if $siswa is NULL, then it will display a 404 page, else it will continue
2/ You can add a simple condition to continue with your data :
$siswa = Siswa::where('nis', $row['nis'])->first();
if ($siswa) {
// then continue
}
First you can $id pass on your public function like
public function show($id)
{
$siswa = Siswa::where('id', $id)->first();
}
You can pass your id on your route

My recursive function in laravel does not call itself

I am writing a recursive function to call the child record from the parent record. It seems not to be working. i am getting this error; "Trying to get property 'refid' of non-object". Where am i getting it wrong. Please any idea? below is the code Snippet.
the function controller
public function DisplayDetail($id)
{
$displayDetail = DB::table('tblmembers')
->where('refid',$id)
->get();
return $this->DisplayDetail($displayDetail->refid);
}
main controller where the function is called
public function dashboard()
{
$profile = DB::table('tblmembers')->where('username',$userid)->first();
$data['userdetail'] = $this->DisplayDetail($profile->memid);
return view('main.userArea',$data);
}
the blade where the record fetched is displayed
#foreach($userdetail as $userd)
{{ $userd->memid }}
#endforeach
my sample data
refid | memid
-------------------
12345 | 123456
123456 | 1234567
123456 | 1234568
123456 | 1234569
1234567 | 1234570
from the above table; refid: 123456 brought memid: 1234567,1234568,1234569. then refid: 1234567 brought memid: 12345670
i want to display all the memid after login in as a user with memid 123456
You are doing one thing wrong in your function DisplayDetail. Here the the correction in your function
If you want to get single item then here is the correct code.
public function displayDetail($id)
{
$displayDetail = DB::table('tblmembers')
->where('refid',$id)
->first();
if($displayDetail) {
$displayDetail['userdetail'] = $this->displayDetail($displayDetail->refid);
}
return $displayDetail;
}
And dashboard function will be look like this
public function dashboard()
{
$profile=DB::table('tblmembers')->where('username',$userid)->first();
$userDetail = $this->DisplayDetail($profile->memid);
return view('main.userArea',[
'userdetail' => $userDetail
]);
}
This is the correct code. Try this and let me know if you have another query on this.
The error:
Trying to get property 'refid' of non-object
is occuring because your database query is using ->get(), which returns a Collection, rather than an object. You cannot get the property ->refid on a Collection, you can only get it from an object that resides in the collection.
As Lakhwinder Singh shows in his code, you need to use ->first(), as this will return one object. I would suggest using ->firstOrFail(), that way you will either get back an object which matches your ID, or it will fail if it cannot find it.
If you do:
$displayDetail = DB::table('tblmembers')
->where('refid',$id)
->firstOrFail();
You will now be able to call:
$displayDetail->refid
You can use that in your function call to displayDetail.
try this function
public function DisplayDetail($id,$data=[])
{
$displayDetail = DB::table('tblmembers')
->where('refid',$id)
->get();
if($displayDetail && isset($displayDetail->refid))// your condition for last child
{
$data = $this->DisplayDetail($displayDetail->refid,$data);
}
$data[] = array('refid' =>$displayDetail->id ,
'memid' => $displayDetail->secondid );
return $data;
}
i'll explain you later first modify according to your requirement and run

Laravel multiple where AND conditions not working

I want to sort the car product details by the below query. But it returns an empty array. Please help me.
public function fetchall($min_price, $max_price, $milage, $old_year, $new_year, $carbrand)
{
$cars = Cars::where([
['price','>=',$min_price],
['price','<=',$max_price],
['year','>=',$old_year],
['year','<=',$new_year],
['milage','=', $milage],
['model_id','=', $carbrand]])->get();
if (!empty($cars)) {
return $cars;
} else {
return "Check your details and submit again";
}
Instead of using !empty($cars) use !$cars->isEmpty().
$cars is an object of Illuminate\Support\Collection so empty() won't work.
See Available Methods for Illuminate\Support\Collection.

Codeigniter query and structure

I have a model with two queries:
function listCategories()
{
$result=$this->db->query("select * from table")->result();
return $result;
}
function listSubCategories($var)
{
$result=$this->db->query("select * from table where field=$var")->result();
return $result;
}
Then i call the first function on my controller:
$data['rows']=$this->my_model->listCategories();
The problem is: now i need to call the second function (listSubCategories()) and the $var that i need to pass to it, is a field from the database which is returned by the listCategories() function
What's the best way to handle a situation like this?
Thanks in advance.
Just pass the return from the first function into your call for the second function:
$data=$this->my_model->listCategories();
$sub=$this->my_model->listSubCategories($data->row()->field_name);

Passing arguments and conditions to model in codeigniter

I'm adding some models to a project, and was wondering if there is a "best practice" kind of approach to creating models:
Does it make sense to create a function for each specific query?
I was starting to do this, then had the idea of creating a generic function that I could pass parameters to. e.g:
Instead of
function getClients(){
return $this->db->query('SELECT client_id,last FROM Names ORDER BY id DESC');
}
function getClientNames($clid){
return $this->db->query('SELECT * FROM Names WHERE client_id = '.$clid);
}
function getClientName($nameID){
return $this->db->query('SELECT * FROM Names WHERE id ='.$nameID);
}
}
Something like
function getNameData($args,$cond){
if($cond==''){
$q=$this->db->query('SELECT '.$args.' FROM Names');
return $q;
}else{
$q=$this->db->query('SELECT '.$args.' FROM Names WHERE '.$cond);
return $q;
}
}
where I can pass the fields and conditions (if applicable) to the model. Is there a reason the latter example would be a bad idea?
Thanks!
I think it would actually be a better idea to use CI's Active Record to compile the queries.
An example:
function all_clients($select)
{
$this->db->select($select);
return $this->_get_client_data();
}
function single_client($select, $id = "")
{
// validate $id
$this->db->select($select);
$this->db->where("id", $id);
$this->db->limit(1);
return $this->_get_client_data();
}
// Only called by a method above once the query parameters have been set.
private function _get_client_data()
{
$q = $this->db->get("clients");
if($q->num_rows() > 0)
{
return $q->result_array();
}
return FALSE;
}
CI's Active Record makes all the stuff you were wanting to much easier. You can imagine setting up your public functions to conditionally set a number of options before actually calling $this->db->get().
I guess you would call _get_client_data a catch-all (?) and running all your data retrieval through a single method makes stuff like error handling much easier to maintain.
NOTE: Always remember to validate data like this. I know you do, but I'm just repeating it.

Resources