I am trying to execute a query using eloquent, however it returns me an array. What I want is to only get the string value of my query.
This is what I get
[{"name":"hey"}] [{"name":"sdasdasd"}]
Here's my eloquent query:
$categoryName = Category::select('name')->where('id', request('category'))->get();
$subCategory = Subcategory::select('name')->where('id', request('subCat'))->get();
as per the Laravel Docs
Retrieving A Single Row / Column From A Table
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:
$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;
If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
so in your example maybe you need to do something like the following :
$subCategory = Subcategory::select('name')->where('id', request('subCat'))-> first();
echo $subCategory->name;
There are so many ways to achive your goal.
Solutions
Use pluck().
$categoryName = Category::select('name')
->where('id', request('category'))
->pluck()
->first();
Use model properties.
$categoryName = Category::find(request('category'))
->name;
If you take only name then follow the below code.
$categoryName = Category::where('id', request('category'))->first()->name;
$subCategory = Subcategory::where('id', request('subCat'))->first()->name;
echo $categoryName;
echo $subCategory;
If you take all columns in a row follow the below code:
$categoryName = Category::where('id', request('category'))->first();
$subCategory = Subcategory::where('id', request('subCat'))->first();
echo $subCategory->name;
echo $categoryName->name;
I hope this i may help you.Try this.
You can get the answer using
$name = DB::table('Category')->where('id','=',request('category'))->pluck('name')->first();
echo $name;
$name = Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
echo $name;
OR
echo Category::select('name')->where('id', request('category'))->take(1)->orderBy('id','asc')->first()->name;
Related
I'm not sure if my title is correctly done, but what I'm trying to do is get all the notifications that a user didn't read.
I have 2 tables the first table is notifications and the second one is read_notifications.
Here is my code in User.php model
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
$unread = Notification::whereNotIn('id', $read)->get();
Here I'm getting all the notification IDs in the read_notifications table and I want to put them in the $unread statement.
The error I get when I do this is
Object of class stdClass could not be converted to string
Notification::whereNotIn('id', $read)->get();
$read is an object and id should be a string (or integer). You should use an id field from your $read object like $read[$i]->id.
Also whereNotIn needs an array as a second argument, so you need to collect your IDs from $read to an array like [1,2,3].
Thanks for helping. I found what I needed, I needed to use the pluck method.
Here is the updated code
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();
for whereNotIn to work $read should be an array.
$read = DB::table('read_notifications')->select('notification_id')->where('user_id', $this->id)->get();
foreach($read as $re)
$ot[] = $re->notification_id;
$unread = Notification::whereNotIn('id', $ot)->get();
OR you can use pluck
$read = DB::table('read_notifications')->where('user_id', $this->id)->pluck('notification_id');
$unread = Notification::whereNotIn('id', $read)->get();
I'm working on laravel array serialize. Below is serialize in controller.
public function CreateSave(CreateTestTopicRequest $request){
...code..
$testtopic->class_room_id = $request->classroom;
$testtopic->roomno = serialize($request->roomno);
...code..
}
Then, roomno will be saved to database like.
a:2:{i:0;s:1:"1";i:1;s:1:"2";}
I would like to get result. For example class_room_id = 1 and roomno only contain in roomno array. I may use command to get all as below.
$testtopics = TestTopic::where('class_room_id',1)->get();
But, I do not know to get record only class_room_id = 1 and roomno contain in array. Any advice or guidance on this would be greatly appreciated, Thanks
You can use like search in json fields
TestTopic::where('class_room_id',1)->where('roomno', 'like', '%"id": 1%')->first()
When checking for an array of values the whereIn method can be used:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$testtopics = TestTopic::where('class_room_id',1)
->whereIn('roomno', unserialize($roomno))
->get();
Multiple where statements can be combined by passing an array:
$roomno = 'a:2:{i:0;s:1:"1";i:1;s:1:"2";}';
$users = TestTopic::where([
['class_room_id', '=', '1'],
['roomno', '=', $roomno],
])->get();
I'm in a situation where I'm doing a MySQL query with Codeigniter and where I have a lot of fields value request which are ALL the same.
Example:
$this->db->query('SELECT * FROM abc WHERE user_id = ? AND msg_from = ? AND msg_to != ?', [$id, $id, $id]);
This has just 3 question marks but the query I'm working on is HUGE and has 19 question marks WHICH ARE ALL THE SAME variable.
So I was trying to figure out how to tell Codeigniter all question marks are pointing to the same variable without having to fill an array with 19 times the same variable.
I thought of a for-loop but I wanted to know if a shortcut exist.
you should be able to do this with Codeigniters Query Builder pretty easily
Something like that should work:
$this->db
->select('*')
->from('abc');
$arrFields = array('users_id', 'msg_from', 'msg_to');
foreach($arrFields AS $val)
{
$this->db->where($val, $id);
}
$query = $this->db->get();
This is the native sql:
$sql = "Select count(name) from users Where email = 't#t.com' and user_id = 10";
I have this laravel code:
$checker = Customer::whereEmailAndUserId("t#t.com",10)->count("name");
Is this a correct way to do it in laravel?
You have to use where helper function and pass an array of checks. For example in your code it will be:
$checker = Customer::where([
['email', '=', 't#t.com'],
['user_id' '=', '10']
])->count();
Note: Please use the appropriate column name as it in table.
Assuming Customer model represents table users, you'll get query with eloquent like this:
Customer::where('email', 't#t.com')->where('user_id', 10)->select(\DB::raw('count(name)'))->get();
The option you are trying is incorrect
here is the right option
$users = \App\Customer::where('email','t#t.com')
->where('user_id',10)
->count()
Explanation of above code
App\Customer is the Model class and I am trying to read records where email = 't#t.com you can use various comparison operators like <,> and so on and you can also use the same function to for string pattern matching also
Eg.
$users = \App\Customer::where('email','%t.com')
->where('user_id',10)
->count()
You can use the same where function for Null Value test also
Eg.
$users = \App\Customer::where('email','=', null)
->where('user_id',10)
->count()
The above where clause will be converted to is null test of the SQL
You can read more here
I tried to get a umat_id with this SQL query :
SELECT umat_id FROM msumat WHERE nama = $nama
I converted this SQL query into CI's Active Record :
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
So this query should return a string (example : "John").
But I got an error when I tried to echo it :
Object of class CI_DB_mysql_result could not be converted to string
I have tried something like this : echo (string)$terdaftar;, but it's not working.
All I want is to echo "John"
EDIT
Just said I want to insert "John" into a variable. How to do that?
$john = ????
As some of the users already pointed the solution, I'm only explaining why you did get this error so you can understand better the querying results that codeigniter gives.
This error:
But I got an error when I tried to echo it : Object of class
CI_DB_mysql_result could not be converted to string
Happens because you were trying to echo an object.
This piece of code
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
Will return an object, this object will have information about the query you've done.
With this object you can get the result(rows) as objects doing this:
$results = $terdaftar->result();
Or you if you feel more comfortable with arrays you can return the results(rows) as an array doing this:
$results = $terdaftar->result_array();
You can also get the number of results doing this:
$number_results = $terdaftar->num_rows()
And this is just an example you can read more about the results here
http://ellislab.com/codeigniter/user-guide/database/results.html
EDIT
A better explanation: imagine that we use the result_array() function to get the result in a pure array format:
$results = $terdaftar->result_array();
Now your variable $results is an array, to iterate through it and get the data you want you'll do something like this:
foreach ($results as $key => $row) {
//the row variable will have each row of your database returned by your query
//so if you want to access a field from that row,
//let's say for example the name field. You would do something like this
if($row['name']=='John')
echo $row['name'];
}
Try:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
foreach ($terdaftar->result() as $row)
{
echo $row->umat_id;
}
Read the documentation for more information.
Try this:
$this->db->select('umat_id');
$terdaftar = $this->db->get_where('msumat', array('nama' => $nama));
$row = $terdaftar->row_array();
$your_variable = $row['umat_id']; /*Here comes your john*/