Get data from database with condition and show it in a view - laravel

This is the data that I have in database
This is what I want to make in the view.blade.php
What I want to do is I want to get the data from the database, if the data inside the column is 1, I want to get the column name as you can see in image 2, but there could be more than 1 column name because the column with data can be column A,B,C... etc.. and I want to show the student name and the subject (a,b,c... etc) if the data in it is '1' in the view. I stuck on how to get all those subject A,B,C.. this is the code that I have written, but it is incomplete because I don't know what to add on it to make it as what I have mentioned above. Hopefully, someone can help me. Thanks in advance
if($row->'A'=='1'){i dont know what should i put here so that i cant get the column name 'A' and print it in view.blade.php}

Assuming your table in database is student_details, create an eloquent model StudentDetail inside app/models/StudentDetail.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class StudentDetail extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'student_details';
/**
* Get subjects in the view
*
* #return string
*/
public function getSubjects()
{
$subjects = [];
$subjects[] = $this->A == 1 ? 'A' : null;
$subjects[] = $this->B == 1 ? 'B' : null;
$subjects[] = $this->C == 1 ? 'C' : null;
$subjects = array_filter($subjects);
return implode(',', $subjects);
}
}
Then you can retrieve data in your controller :
public function view()
{
$studentDetails = StudentDetail::get();
return view('view.path', compact('studentDetails'));
}
And inside view you can do :
#foreach($studentDetails as $detail)
{{ $detail->name }} : {{ $detail->getSubjects() }}
#endforeach
You can use appended property as well, I have not used that because appended property is added every-time when model is instantiated. I believe having it in a function makes it flexible to use as and when needed.

Okay i tried it bit different way it's not proper but it will give you desired output you want :-
Route::get('/test',function(){
$query = TestTable::all();
$calculateData = [];
foreach ($query as $key){
$subjects = '';
if($key->A === 1){
$subjects .= 'A';
}
if($key->B === 1){
$subjects .= 'B';
}
if($key->C === 1){
$subjects .= 'C';
}
$calculateData[] = [$key->name,$subjects];
}
foreach ($calculateData as $key){
dump("NAME : " . $key[0]."Subject : " . $key[1]);
}
dd("STOP");
})->name('test');

Related

Can't filter data from database using getSelect()->where() Magento 2

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!
I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

codeigniter - compare values

I need to compare two values in a table: cliente and nro_cuota, if both exist I don't want to add it.
Here is my code
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('cobranzas');
$crud->set_subject('Cobranzas');
$crud->set_language('spanish');
$crud->required_fields(
'id',
'cobrador',
'cliente',
'nro_cuota'
);
$crud->columns(
'cobrador',
'cliente',
'nro_cuota'
);
$crud->set_relation('cobrador', 'cobradores', 'apellido_nombre');
$crud->set_relation('cliente', 'clientes', 'apellido_nombre');
$output = $crud->render();
$this->load->view('cobranzas/cobranzas_v', $output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
and I wrote a model, I`m not sure if this is the right way, but I don't know how I must call it
class Compare_values_model extends CI_Model
{
public function compare($id)
{
$this->db->select('"SELECT * FROM `cobranzas` WHERE `cliente` = '$cliente' AND `nro_cuota` = '$nro_cuota'"');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
}
Hope can help me I couldn't find some examples on internet to learn more, thanks in advance.
You said I need to compare two values in a table: cliente and nro_cuota, if both exist I don't want to add it. But you are matching the variables with fields. So just check not equal as below:
$query = $this->db->query("SELECT * FROM `cobranzas` WHERE `cliente` <> '$cliente' AND `nro_cuota` <> '$nro_cuota'");
Note: Remove extra single quote in your query

accessing data linked by foreign key in site view of custom component

In my custom component, in site view, I have a list of countries (view: countries). Clicking on a country, another view is displayed (view: persons) showing all persons living in that country.
Now, in persons view, I want to display the country's name and flag.
So I want to add a function getCountry() in ...site/models/persons.php:
public function getCountry() {
$db = $this->getDBO();
$id = $this->state->get("filter.country");
$sql = "SELECT * FROM #__cnlp_persons_country WHERE id = $id";
$db->setQuery($sql);
$country = $db->loadResult();
// var_dump($country);
return $country;
}
Then, I added to .../site/views/persons/view.html.php:
class Cnlp_personsViewPersons extends JView
{
protected $items;
protected $state;
protected $params;
protected $country; // <--- I added this
...
public function display($tpl = null)
{
$app = JFactory::getApplication();
$this->state = $this->get('State');
$this->items = $this->get('Items');
$this->params = $app->getParams('com_cnlp_trainers');
$this->country = $this->get('Country'); // <--- I added this
(...)
Result: I thought I could then in ---/site/views/persons/tmpl/default.php something like...
<h1><?php echo $this->country->name; ?></h1>
<img src="<?php echo $this->country->flag; ?>" />
...but I get no output...
What did I do wrong?
$db->loadResult(); is used to load a single value results (for example if you would only want to select the country name or something like this), but in your query you're selecting an entire row, so you should use one of theese:
$db->loadRow(); // returns an indexed array from a single record in the table
$db->loadAssoc(); // returns an associated array from a single record in the table
$db->loadObject(); // returns a PHP object from a single record in the table:
You can read more about this here (it's joomla 1.5 documentation, but it's same for 2.5 and 3)

Array from Controller to model [codeIgniter]

here's my problem:
Codeigniter's doc says this :
<?php
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
?>
I just want to pass conditions to my where clause from controller to model so :
Controller
<?php
$condition = array('id' => $id_user)
$data['info_user'] = $this->user_model->get_user($condition);
?>
Model
public function get_user($condition)
{
$q = $this
->db
->where($condition)
->get('users');
if($q->num_rows > 0)
{
return $q->row();
}
}
This return : SELECT * FROM (users) WHERE 3 IS NULL
But when I put my array directly in the model ($
There is no need to pass an array and I'm not even positive that it can be done the way you're trying to do it. Just pass the value itself to the model as below. Answer edited to show multiple variables.
Controller:
$data['info_user'] = $this->user_model->get_user($id_user,$user_login);
Model:
public function get_user($id_user,$user_login)
{
$q = $this
->db
->where('id_user',$id_user)
->or_where('user_login',$user_login);
->get('users');
if($q->num_rows == 1)
{
return $q->row();
}
}
As a side note when you want a single result from your database, as in retrieving a user ALWAYS check for a single result and not > 0. You want to ensure you're only getting one user back.

Getting data from model to controller

I do have a question : I cannot pass the data from model to controller
You can see some of my codes, please help me.
It does not work!
this is my model "mymodel.php"
....
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
if($query){
foreach ($query->result() as $row);
}
$t = "EXAMPLE/{$row->code}";
function wandad() {
return $t;
}
.....
and this is my controller mycont.php
...
$this->load->model('mymodel');
$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
...
and this is my view myview.php
....
echo $new;
.....
Clearly you The model is not written properly and to corrent this simple do this
1.) I put a default value on $t
2.) I put the query >> loop on the inside function
wandad
so it can be executed once called from controller
function wandad() {
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
$t = "";
if($query){
foreach ($query->result() as $row){
$t = "EXAMPLE/{$row->code}".'<br>';
}
}
return $t;
}
Here are several issues into your model
Your Foreach function doesn't do anything
$t is not in the same namespace than wandad()
Function wandad is not defined into your model class
I'm not sure of what you wanna get with wandad() function but here's a pattern.
function yourFunction()
{
/* This will return the full query as an array */
$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
/* Store variable in the same class */
$this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
return $this->t;
}
Then into your controller, do that instead :
$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);
#Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.
There is a small mistake in your code #Ernesto.that is
foreach ($query->result() as $row){
$t. = "EXAMPLE/{$row->code}".'<br>';
}
but your code was simply nice

Resources