DB Query on returning one value Laravel - mysql

Im using a simple query to pull the users in a table called users.
$users = DB::table('users')->get();
Then using a foreach loop to get the values , for example :
foreach ($users as $user)
{
return $user->email;
}
There is definitely 2 records in the DB Table, but it only returns one line. If i try to query a different table it does the same thing.
If i use the Query Log between the query
DB::enableQueryLog();
$users = DB::table('users')->get();
$result = DB::getQueryLog();
It returns the query and it looks fine
[{"query":"select * from `users`","bindings":[],"time":0.85}]
This table was created within PhpMyAdmin and not using the Artisan Migrate

Of course it so, cause you return from loop, use echo
foreach ($users as $user)
{
echo $user->email;
}
return statement inside the loop will behave like break for your case, this means breaking the loop.

You can use either:
DB::table('users')->select(['email'])->get();
or
DB::table('users')->get(['email']);
But its basics, you can easily find this stuff in docs https://laravel.com/docs/master/

Related

Need suggestion in query builder of Laravel 9 application

How to avoid foreach-loop because Laravel query builder is used to get a single record detail.
When I tried without foreach-loop, the following error occurred "Property [name] does not exist on this collection instance".
Controller
public function show(Student $student)
{
$result = DB::table('students')
->select('*')
->where('id', "=" ,$student['id'])
->get();
foreach($result as $studentData){}
return view('student.show', ['studentData' => $studentData]);
}
Blade View
{{ $studentData->name}}
->get() always returns a Collection, even if there's only one match. If you only want the first record, you can use ->first() instead.
Do you really have to use raw queries? I assume Student is a Laravel Model, in that case, you should be able to use Student::find($id) to get the model directly.

Laravel Select Query Accessing Returned Data

I've been working with Laravel for a short time, and am confused about accessing data retrieved from queries. I'm trying to save data to variable but am getting the following:
Trying to get property of non-object
Queries tried:
$data = DB::table('table_1')->select('user_id', 'email')->where('email', '=', Input::get('email_address'))->get();
// also tried
$data = DB::table('table_1')->where('email', '=', Input::get('email_address'))->pluck('user_id');
// accessing data
$userID = $data->user_id;
Both return the same.
To elaborate a little bit, ->get() will return a Collection. You might iterate over it as an array, but you can profit from methods that this class offers. pluck is one of these.
That's why $userID = $data->user_id; wouldn't work.
first() did the trick, rather than get().
$data = DB::table('table_1')->select('user_id', 'email')->where('email', '=', Input::get('email_address'))->first();

mySQL query for building dynamically populated model

I have some code below which demonstrates a hard-coded example of what I would like to accomplish dynamically.
At a high level, I wish to do something like select * from view_data_$app_state and then get all of the data from that views table into my mustache templates dynamically.
The code I currently must use to group multiple rows of data for a specific column along with the views data is:
<?php
error_reporting(E_ALL);
class Example {
function __construct(){
try {
$this->db = new PDO('mysql:host=localhost;dbname=Example', 'root','drowssap');
}
catch (PDOException $e) {
print($e->getMessage());
die();
}
}
function __destruct(){
$this->db = null;
}
function string_to_array($links_string){
return explode(",", $links_string);
}
function get_view_data(){
$q = $this->db->prepare('select *, GROUP_CONCAT(`links`) as "links" from `view_data_global` ');
$q->execute();
$result = $q->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
$Example = new Example();
$result = $Example->get_view_data();
$result[0]["links"] = $Example->string_to_array($result[0]["links"]);
echo json_encode($result);
This gives me the perfect object while
GROUP_CONCAT seems to be doing the trick this way, however I MUST know the column name that will contain multiple rows before writing the query. I am trying to figure out an approach for this and wish to make a custom query + code example that will transform cols with multiple rows of null null and not empty data into an array like above - but return the data.. again like the code above.
Below is an output of the actual data:
[{"id":"1","title":"This is the title test","links":["main","about","store"]}];
How can I replicate this process dynamically on each view table?
Thank you so much SO!
You can use PDOStatement::fetch to retrieve your results, with fetch_style set to PDO::FETCH_ASSOC (some other values will also provide the same information). In this case, the result set will be array indexed by column name. You can access this information with foreach (array_expression as $key => $value)
See the documentation for additional information.

laravel how to handle empty json results set from a query

I am very new to the laravel framework and i have what it seems to be a simple question. I have a query like so
$query['query2']= DB::connection('test')->select(
"select * from cities");
...
...
echo json_encode($q);
Sometimes this particular query returns an empty result set.
How do I handle this? Lets say I want to add my own json response when its empty.
Thanks
Try the following
$dataToSend = $q->get(); // $q being your query
if($dataToSend->isEmpty())
{
echo json_encode(['something'=>'else']);
}
else
{
echo json_encode($dataToSend);
}
Or in a shorter fashion
$dataToSend = $q->get(); // $q being your query
echo json_encode($dataToSend->isEmpty()? ['something'=>'else'] : $dataToSend);

What is wrong with this Code Igniter mySQL query?

I have two tables for storing information about a user. One is for authentication, the other is information the user will enter themselves. I am writing a model that will be used when the user interacts with this information. The following method is to return data for display and modification.
I need a query that will return 'email' and 'username' from $accounts_table and * from $profiles_table. I can't seem to get my head around the JOIN syntax though. I understand how joins work, but my queries throw sentax errors.
function get_userdata($id){
$data = array();
$this->db->get_where($this->profiles_table, array('user_id' => $id));
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data= $this->db->get();
return $data;
}
I see a couple of issues:
You should be using $this->db->where(), instead of $this->db->get_where(). get_where() executes the query immediately.
$this->db->get_where('user_id', $id);
Also the first argument of $this->db->join() should only be the table name, excluding the field.
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
And you're returning $data which is just an empty array(). You would need to pass the query results to $data like this:
$data = $record->result_array();
get_where executes the query. So, your join is its own query, which doesn't work.
You need to break get_where into where and from.
Also, in MySQL, you JOIN a table, not a field. If you want that field, add it to the SELECT.
$this->db->select($this->profiles_table.'.*');
$this->db->select($this->accounts_table.'.email,'.$this->accounts_table.'.username');
$this->db->from($this->profiles_table);
$this->db->where('user_id', $id);
$this->db->join($this->accounts_table, $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
$data = $this->db->get();
NOTE: $this->db->get() returns a query object, you need to use result or row to get the data.
I think you've a mistake:
$this->db->join($this->accounts_table.'.email', $this->accounts_table.'.id = '.$this->profiles_table.'.user_id');
First parameter should a table NOT a field: $this->accounts_table.'.email' is wrong IMHO. Or only a typo :)