How to fetch data from a json with laravel - json

I premise that I'm new to the Laravel environment.
I have this JSON file in the database
{
"48:CE:B8:09:7D:AD": ["-91"],
"70:61:91:66:6B:1E": ["-81", "-69", "-79", "-65", "-74"],
"4B:6F:42:53:EB:82": ["-84", "-73", "-81"],
"77:87:80:27:2B:31": ["-83", "-70", "-82", "-71", "-79", "-71", "-79", "-71", "-80", "-72"],
"43:FD:25:20:5A:7B": ["-76", "-84", "-76", "-88", "-77", "-86"],
"C1:04:08:03:3C:05": ["-73"],
"7F:D2:44:60:82:BD": ["-88", "-79", "-88"],
"FE:47:DA:73:90:29": ["-55", "-43", "-59", "-35", "-46", "-38", "-49"],
"62:46:58:C8:A9:9A": ["-68", "-77", "-68"],
"68:13:E4:00:12:30": ["-68", "-81"],
"4E:0D:D6:41:77:FA": ["-68", "-77", "-68", "-76", "-68", "-79", "-71"],
"71:B0:03:A6:17:A5": ["-82", "-73", "-81", "-73"],
"19:F2:64:21:35:B5": ["-74", "-65", "-77", "-69", "-78", "-69"],
"5C:D5:BA:32:06:AD": ["-86"],
"11:91:3D:57:0E:F0": ["-90", "-82"],
"44:08:E7:5C:56:B3": ["-89", "-80"],
"58:99:6F:53:65:C8": ["-77", "-85"],
"54:3C:61:D8:5B:DD": ["-88", "-79"],
"59:02:8C:78:5D:E1": ["-85", "-73", "-82", "-69", "-84", "-75", "-83", "-71"],
"64:F0:DC:95:6E:16": ["-86", "-78"],
"71:E5:42:BA:19:F4": ["-91", "-77", "-86", "-73", "-84", "-74", "-84"],
"E1:63:14:57:89:25": ["-48", "-57", "-38", "-47"],
"57:7D:E9:6F:06:24": ["-85"],
"56:B2:4B:5B:7E:2E": ["-88", "-80"],
"64:3D:02:D4:ED:4E": ["-76", "-64", "-72"],
"0C:93:8F:E5:C6:2A": ["-76", "-66"],
"3F:47:42:77:BD:9A": ["-64", "-83"],
"3C:46:5E:20:9A:FE": ["-79", "-57", "-74"],
"67:58:EE:A8:9D:CC": ["-64", "-80"],
"C4:A5:DF:24:05:7E": ["-65"],
"79:B8:3B:90:31:12": ["-89", "-71", "-88", "-75"],
"75:8E:FE:9B:69:DA": ["-93"],
"49:BE:B0:74:7A:71": ["-66", "-82"],
"55:33:20:52:E1:EC": ["-75"],
"45:D3:80:F3:A4:59": ["-79", "-71"],
"44:CA:8A:EF:31:45": ["-92", "-78"],
"5F:0D:99:F8:EE:94": ["-83"]
}
and I would like to get only some MAC addresses and respective RSSI values using Laravel.
My Model is the following:
class DataFromRasp extends Model
{
use HasFactory;
public $timestamps = false;
protected $primaryKey = 'id';
protected $fillable = ['device'];
protected $casts = ['device' => 'array'];
}
And my controller:
class DataFromRaspController extends Controller
{
public function index()
{
$data=DataFromRasp::all();
return view('backend.auth.user.dictionary', compact("data"));
}
public function create()
{
}
public function store(Request $request)
{
}
public function show(DataFromRasp $dataFromRasp)
{
}
public function edit(DataFromRasp $dataFromRasp)
{
//
}
public function update(Request $request, DataFromRasp $dataFromRasp)
{
//
}
public function destroy(DataFromRasp $dataFromRasp)
{
//
}
public function getDict(Request $request)
{
$data = $request->get('jsondata');
$data = json_decode($data, true);
DataFromRasp::create(['device' => $data]);
return back()->with('success', 'Data successfully store in json format.');
}
}
The getDict() function receives the JSON from a raspberry and saves it in the DB.
The structure of the DB table is as in figure
https://imgur.com/a/pwsaIeM
I need the values of the MAC addresses "E1:63:14:57:89:25" and "FE:47:DA:73:90:29", how can I get them?

Related

PHP OOP INSERT INTO only insert NULL in Database

I'm trying to add members in my database using OOP, however it only insert NULL values
It works perfectly fine when I'm not using OOP
Here is my PHP code :
$request = $bdd->query('SELECT id_membre, prenom, nom, ville FROM client');
class Membre {
private $_id;
private $_prenom;
private $_nom;
private $_ville;
/*HYDRATATION*/
public function hydrate(array $donnees) {
foreach($donnees as $key => $value) {
$method = 'set'.ucfirst($key);
if (method_exists($this, $method)) {
$this->$method($value);
}
}
}
public function id() { return $this->_id; }
public function prenom() { return $this->_prenom; }
public function nom() { return $this->_nom; }
public function ville() { return $this->_ville; }
public function setId($id) {
$this->_id = $id;
}
public function setPrenom($prenom) {
$this->_prenom = $prenom;
}
public function setNom($nom) {
$this->_nom = $nom;
}
public function setVille($ville) {
$this->_ville = $ville;
}
}
That part seems to be working fine
class MembreManager {
private $_bdd;
public function __construct($bdd){
$this->setBdd($bdd);
}
public function add(Membre $mbr) {
$q = $this->_bdd->prepare("INSERT INTO client(prenom, nom, ville)
VALUES(:prenom, :nom, :ville)");
$q->bindValue(':prenom', $mbr->prenom());
$q->bindValue(':nom', $mbr->nom());
$q->bindValue(':ville', $mbr->ville());
$q->execute();
}
}
$mbr = new Membre([
'nom' => 'Name',
'prenom' => 'Surname',
'ville' => 'City',
]);
$manager = new MembreManager($bdd);
$manager->add($mbr);
while($donnees = $request->fetch()) {
$mbr = new Membre($donnees);
}
Inserting values only seems to work when I manually input string in my Insert Into.

How to get Sum from relationship in laravel

//Client Model
protected $fillable = [
'client_name', 'plan_id', 'client_type'
];
public function plan(){
return $this->belongsTo(Plan::class, 'plan_id', 'id');
}
// Plan Model
protected $fillable = [
'price'
];
public function clients()
{
return $this->hasMany(Client::class);
}
I want to get total price of all clients where client_type = something
I would do it like this:
function getClientTypeTotal($clientType)
{
return Client::where('client_type', $clientType)->get()->sum(function ($client) {
return $client->plan->price;
})
}

Can not pull updated data from mysql database

My ASP.NET MVC & EF project has a base controller as follows:
public class BaseController : Controller
{
private Context _database;
public Context Db
{
get
{
if (_database == null)
{
_database = new Context();
}
return _database;
}
}
protected override void Dispose(bool disposing)
{
if (_database != null)
{
_database.Dispose();
}
base.Dispose(disposing);
}
My ajax save setting code is:
public JsonResult SiteGenelAyarlari(List<GeneralSettings> gs)
{
if (ModelState.IsValid)
{
gs.ForEach(item => Db.GeneralSettings.AddOrUpdate(s => s.LanguageId, item));
Db.SaveChanges();
}
return Json("Saved fine.", JsonRequestBehavior.AllowGet);
}
But when I update a value in the database, after a page refresh the new values do not get pulled. What am I missing?
If I re-run project, new values are being returned fine.

Zend - Losing post values in Mapper

I seem to be losing my post data when passing it from my Controller to my Mapper to insert into my DB. I'm new to this and using the Guestbook template but modified it to be adding a "deal". This is what I have:
Controller
public function newAction()
{
$request = $this->getRequest();
$form = new Application_Form_Deal();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
$posts = $form->getValues();
//print_r($posts);
$newdeal = new Application_Model_Deal($posts);
$mapper = new Application_Model_DealMapper();
$mapper->save($newdeal);
return $this->_helper->redirector('index');
}
}
$this->view->form = $form;
}
This is my Mapper
public function save(Application_Model_Deal $deal)
{
$data = array(
'dealname' => $deal->getDealName(),
'dealclient' => $deal->getDealClient(),
'dealtelephone' => $deal->getDealTelephone(),
'dealvalue' => $deal->getDealValue(),
'dealdescription' => $deal->getDealDescription(),
'dealcreated' => date('Y-m-d H:i:s'),
'dealmodified' => date('Y-m-d H:i:s'),
);
/*echo "<pre>";
print_r($data);
echo "</pre>";
exit();*/
if (null === ($dealid = $deal->getDealId())) {
unset($data['dealid']);
$this->getDbTable()->insert($data);
} else {
$this->getDbTable()->update($data, array('dealid = ?' => $dealid));
}
}
protected $_dealmodified;
protected $_dealcreated;
protected $_dealdescription;
protected $_dealvalue;
protected $_dealtelephone;
protected $_dealclient;
protected $_dealname;
protected $_dealid;
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function __set($name, $value)
{
$method = 'set' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
$this->$method($value);
}
public function __get($name)
{
$method = 'get' . $name;
if (('mapper' == $name) || !method_exists($this, $method)) {
throw new Exception('Invalid deal property');
}
return $this->$method($value);
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key => $value) {
$method = 'set' . ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setDealModified($ts)
{
$this->_dealmodified = $ts;
return $this;
}
public function getDealModified()
{
return $this->_dealmodified;
}
public function setDealCreated($ts)
{
$this->_dealcreated = $ts;
return $this;
}
public function getDealCreated()
{
return $this->_dealcreated;
}
public function setDealDescription($text)
{
$this->_dealdescription = (string) $text;
return $this;
}
public function getDealDescription()
{
return $this->_dealdescription;
}
public function setDealValue( $text)
{
$this->_dealvalue = $text;
return $this;
}
public function getDealValue()
{
return $this->_dealvalue;
}
public function setDealTelephone($text)
{
$this->_dealtelephone = $text;
return $this;
}
public function getDealTelephone()
{
return $this->_dealtelephone;
}
public function setDealClient($text)
{
$this->_dealclient = $text;
return $this;
}
public function getDealClient()
{
return $this->_dealclient;
}
public function setDealName($text)
{
$this->_dealname = $text;
return $this;
}
public function getDealName()
{
return $this->_dealname;
}
public function setDealId($dealid)
{
$this->_dealid = (int) $dealid;
return $this;
}
public function getDealId()
{
// $this->_dealid = (int) $value;
return $this->_dealid;
}
I am a complete loss as to why, when I print_r my $data var in the Mapper everything is gone.
Please help!
This looks odd $mapper->save($newdeal, $posts);
your api is save(Application_Model_Deal $deal)
so it should read $mapper->save($newdeal);.
if you really want to get a handle on mappers and models, these three links helped me alot:
http://survivethedeepend.com/
http://phpmaster.com/building-a-domain-model/
http://phpmaster.com/integrating-the-data-mappers/
You are after a specific work flow :
present form
collect from data (the $post)
validate $post data (if(isValid())
get valid and filtered form values ($form->getValues())
instantiate your deal object ($newdeal = new Application_Model_Deal($posts);)
save/update your deal with your mapper
on success redirect
once your deal object is created the $post data has no further value and the deal object is the important thing to think about. Hope this helps a bit.
Ok I think I found it:
your problem revolves around this $method = 'set' . ucfirst($key); this line will try and call $this->setProperty(); your getters and setters are set up camel case so they won't work. The easiest way to fix this is to rename your getters and setters to:
public function setDealmodified($ts)//not camel cased only first letter is capped.
{
$this->_dealmodified = $ts;
return $this;
}
or you have to camel case your array keys.
Your save() method in the mapper does not have a second argument which you used as your $post parameter.
Refactor:
public function save(Application_Model_Deal $deal, array $post)...

unserialize pdo mysql error - invalid data source name

I have these classes below for my online store.
This super class holds all common methods used by the child classes.
class grandpa
{
public function test1($string)
{
return $string;
}
}
So do the PDO connection,
class database_pdo extends grandpa
{
protected $connection = null;
protected $dsn,$username,$password;
public function __construct($dsn,$username,$password)
{
$this->dsn = $dsn;
$this->username = $username;
$this->password = $password;
$this->get_connection();
}
public function get_connection()
{
try
{
$this->connection = new PDO($this->dsn, $this->username, $this->password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
$this->get_error($e);
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->get_connection();
}
public function get_error($e)
{
$this->connection = null;
die($e->getMessage());
}
public function __destruct()
{
$this->connection = null;
}
}
I have this class extend from pdo for other common methods that require pdo connection,
class papa extends database_pdo
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}
The child classes,
class kido_1 extends papa
{
public function __construct($connection)
{
parent::__construct($connection);
}
public function test3($string)
{
return $string;
}
}
How it use the classes above,
# Host used to access DB.
define('DB_HOST', 'localhost');
# Username used to access DB.
define('DB_USER', 'xxx');
# Password for the username.
define('DB_PASS', 'xxx');
# Name of your databse.
define('DB_NAME', 'xxx');
# Data source name.
define('DSN', 'mysql:host='.DB_HOST.';dbname='.DB_NAME);
$connection = new database_pdo(DSN,DB_USER,DB_PASS);
$kido = new kido($connection);
$_SESSION['cart'] = serialize($kido);
$kido = unserialize($_SESSION['cart']);
print_r($kido->test3('hello'));
I get this error,
invalid data source name
It is caused by unserialize() that I need it for my cart data...
How can I fix this? Or a better way of rewrite these classes?
Your papa::connection is a PDO object. Therefore, when you are trying to serialize $kido, you are trying to serialize a resource, which is not possible.
Try adding a $this->connection = null; in your database_pdo::__sleep() method.
a solution I think...
class papa extends grandpa
{
protected $connection = null;
public function __construct($connection)
{
$this->connection = $connection;
}
public function test2($string)
{
return $string;
}
}