I am trying to save this user edit to a data base but it's not working - laravel-5.1

My model:
static public function userEddit($request){
$user = new self();
$user->name = $request['name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
DB::insert('INSERT INTO users_role VALUES(' . $user->id .',5)');
}
My UserContorller
public function postUser(PostUser $request){
User::userEddit($request);
return redirect('shop');
}

Related

I don't understand the purpose of code snippet

In Zend Frameword 2.5 a review and saw some code, it works fine but my IDE shows error about it.
I don't know purpose of this code snippet.
Why to write: $this->table = clone $this->table;
Github Link: https://github.com/zendframework/zend-db/blob/master/src/TableGateway/AbstractTableGateway.php
Function: rows 529-544
Please explain to me about it.
public function __clone()
{
$this->resultSetPrototype = (isset($this->resultSetPrototype)) ? clone $this->resultSetPrototype : null;
$this->sql = clone $this->sql;
if (is_object($this->table)) {
$this->table = clone $this->table;
} elseif (
is_array($this->table)
&& count($this->table) == 1
&& is_object(reset($this->table))
) {
foreach ($this->table as $alias => &$tableObject) {
$tableObject = clone $tableObject;
}
}
}
I can't understand Zend purpose but i hope after run two below code snippet, from different two results, you can understand
<?php
class A {
public $foo = 1;
}
class B {
protected $value = 1;
protected $bar = null;//
public function __construct() {
$this->bar = new A();
}
public function setValue($foo = 3){
$this->value = $foo;
}
public function setFooBar($foo = 3){
$this->bar->foo = $foo;
}
public function __clone() {
$this->bar = clone($this->bar);
}
}
$a = new B();
$c = clone($a);
$c->setFooBar(3);
$c->setValue(6);
var_dump($a);
echo "\n";
var_dump($c);
?>
<?php
class A {
public $foo = 1;
}
class B {
protected $value = 1;
protected $bar = null;//
public function __construct() {
$this->bar = new A();
}
public function setValue($foo = 3){
$this->value = $foo;
}
public function setFooBar($foo = 3){
$this->bar->foo = $foo;
}
}
$a = new B();
$c = clone($a);
$c->setFooBar(3);
$c->setValue(6);
var_dump($a);
echo "\n";
var_dump($c);
?>
clone (or __clone) is a so called magic method. Check for reference on other magic methods the php documentation on magic methods here.
Check also the specific documentation for clone where they explain the working of this magic method:
An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.
In other words it allows you to define custom cloning behavior for an object instance inside its class definition using a public __clone method. This method will be called "magically" when you do:
$clone = clone $instance;

Zend Framework Sql not finding column

I'm having an issue with Zend Framework 2's SQL class. It's saying it cannot find a certain column in the table but the column is there. I've run into this problem before and had to use actual SQL syntax instead of building the query. I rather not have to resort to putting the actual syntax in and instead figure out why this is happening so I can avoid having this issue in the future.
Here is my code:
namespace Members\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Select;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Predicate;
use Members\Model\Interfaces\FeedInterface;
use Members\Model\Exceptions\FeedException;
class FeedModel implements FeedInterface
{
/**
* #var TableGateway
*/
public $gateway;
/**
* #var string
*/
public $user;
/**
* #var Sql
*/
public $sql;
/**
* #var Select
*/
public $select;
/**
* Constructor method for FeedModel class
* #param TableGateway $gateway
* #param string $user
*/
public function __construct(TableGateway $gateway, $user)
{
$this->gateway = $gateway instanceof TableGateway ? $gateway : null;
$this->select = new Select();
$this->sql = new Sql($this->gateway->getAdapter());
$this->user = $user;
}
/**
* {#inheritDoc}
* #see \Members\Model\Interfaces\FeedInterface::listFriendsStatus()
*/
public function listFriendsStatus()
{
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = $this->select->columns(array('*'))
->from('friends')
->where(array('user_id' => $this->getUserId()['id'])); // the issue
file_put_contents(getcwd() . '/public/query.txt', $this->sql->buildSqlString($friend_query));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result;
}
$this->select->columns(array('status'))
->from('status')
->where(array('id' => array_values($friend_id), new Predicate\IsNotNull('id')));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$this->select->columns('username')
->from('members')
->where(array('id' => array_values($friend_id), new Predicate\IsNotNull('id')));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
$status_dir = array();
foreach ($image_query as $value) {
if (#!is_dir(getcwd() . '/public/images/profile/' . $value['username'] . '/status/')) {
continue;
}
$status_dir[] = getcwd() . '/public/images/profile/' . $value['username'] . '/status/';
}
$images = array();
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir, 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows;
}
return array('status' => $status, 'images' => $images);
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
/**
* {#inheritDoc}
* #see \Members\Model\Interfaces\FeedInterface::hideFriendsStatus()
*/
public function hideFriendsStatus($friend_id)
{
}
/**
* Grabs the user id for the user
*
* #return int|boolean
*/
public function getUserId()
{
$this->select->columns(array('*'))
->from('members')
->where(array('username' => $this->user));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($this->select),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
foreach ($query as $result) {
$row = $result;
}
return $row;
}
return false;
}
}
This is the exception message I am getting:
PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_id' in 'where clause'
But as you can see in this screenshot, the column user_id exists in the friends table I have in place:
So my question is why is it doing this and how can I in the future avoid this issue?
Thanks!
It looks like the select is causing the issue.
Since your code ->from('friends') is called first and then it is overridden due to this function call $this->getUserId(), which overrides the friends table to members due to ->from('members').
Try changing your code to.
$userId = $this->getUserId()['id'];
$friend_query = $this->select->columns(array('*'))
->from('friends')
->where(array('user_id' => $userId));
This should work, but if it doesn't, try to just create new select object $select = new Select(); in both the functions rather than $this->select = new Select();.

Flume Custom Interceptor is not Working

I want to change IP address in data by its mask IP. This is done in the "backup" part of my Flume agent (see below).
In this configuration there are 2 channels: the first channel dumps data to HBase, while the second one is used for backup:
a1.sources = r1 r2
a1.channels = channel1 Backup_channel
a1.sinks = FSink
a1.sources.r1.handler = com.flume.handler.JSONHandler
a1.sources.r1.type = avro
a1.sources.r1.bind = x.x.x.x
a1.sources.r1.port = 10008
a1.sources.r2.handler = com.flume.handler.JSONHandler
a1.sources.r2.type = avro
a1.sources.r2.bind = x.x.x.x
a1.sources.r2.port = 10009
a1.sources.r2.interceptors = i1
a1.sources.r2.interceptors.i1.type = com.flume.interceptor.DcInterceptor
a1.channels.channel1.type = file
a1.channels.channel1.checkpointDir = /root/flume/channels/Livechannel/checkpoint
a1.channels.channel1.dataDirs = /root/flume/channels/Livechannel/data
a1.sinks.FSink.type = hbase
a1.sinks.FSink.table = Temp_Test
a1.sinks.FSink.batchSize = 300
a1.sinks.FSink.columnFamily = T
a1.sinks.FSink.serializer = com.flume.sink.TestTP
a1.sources.r1.channels = channel1
a1.sources.r2.channels = Backup_channel
a1.channels.Backup_channel.type = file
a1.channels.Backup_channel.checkpointDir = /data/disk/flume/backup/checkpoint
a1.channels.Backup_channel.dataDirs = /data/disk/flume/backup/data
a1.sinks.FSink.channel = channel1
Following is my custom Java Interceptor Code. It implements the interception method, which get an IP address from the body, calculates its IP mask and then adds it to the body. But somehow it's not working:
public class DcInterceptor implements Interceptor {
private byte[] jsonTestBeans;
private final Type listType = new TypeToken < List < TestBeans >> () {}.getType();
#Override
public void close() {
// TODO Auto-generated method stub
}
#Override
public void initialize() {
// TODO Auto-generated method stub
new Logger();
}
#Override
public Event intercept(Event event) {
// TODO Auto-generated method stub
List < Row > actions = new ArrayList < Row > ();
this.jsonTestBeans = event.getBody();
Logger.logger.debug("In Interceptor");
System.out.println("In Interceptor");
Gson _Gson = new Gson();
String jsonstr = "";
try {
jsonstr = new String(jsonTestBeans, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
Logger.logger.error(e.getMessage() + "In Interceptor");
jsonstr = new String(jsonTestBeans);
}
List < TestBeans > TestBeanss = _Gson.fromJson(jsonstr, listType);
System.out.println("Json String :" + jsonstr);
List < String > gTouch = new ArrayList < String > ();
for (TestBeans TestBeans: TestBeanss) {
String str = TestBeans.getIp();
Logger.logger.debug("IP : " + str);
String st = (str.substring(0, str.lastIndexOf(".") + 1) + "x");
Logger.logger.debug("Mask IP : " + st);
TestBeans.setRemoteIp(st);
}
event.setBody(_Gson.toJson(TestBeanss).getBytes());
Logger.logger.debug("Interceptor Ends");
return event;
}
#Override
public List < Event > intercept(List < Event > events) {
// TODO Auto-generated method stub
System.out.println("In List Interceptor");
Logger.logger.debug("In List Interceptor");
for (Event event: events) {
intercept(event);
}
return events;
}
public static class CounterInterceptorBuilder implements Interceptor.Builder {
private Context ctx;
#Override
public Interceptor build() {
Logger.logger.debug("In Interceptor Build");
System.out.println("In Build Interceptor");
return new DcInterceptor();
}
#Override
public void configure(Context context) {
this.ctx = context;
}
}
At least, I can see:
The configuration lines regarding your interceptor refer to an agent called ECircleTp_Test, while the rest of the configuration refer to a1.
You have configured com.flume.interceptor.DcInterceptor2, but the interceptor class you have developed is called DcInterceptor (without the final 2).
You have configured com.flume.interceptor.DcInterceptor2 as the fully qualified class name of your custom interceptor. Nevertheless, the code of the interceptor does not declare any package for the DcInterceptor(2) class.

What kind of object has to be passed for JsonResult in MVC.Net

So I'm passing a custom class to my controller and it seems that the JsonResult is not properly passed.
What bothers me is that (also the fullcalendar wont read the json) the console.log which I have in my view prints the path to the function (wtf?) instead of what Json shoul return
This is my code:
public JsonResult GetCalendarEvents()
{
var eventList = BusinessLayer.Event.getAllEvents();
return Json(eventList.ToArray(), JsonRequestBehavior.AllowGet);
}
What kind of object has to be passed for this to work?
My evenList is of type List<Event> from here:
public static String ListToString(List<Event> evs)
{
String ret = "";
foreach (var ev in evs)
{
ret += ev.ToString() + "\n";
}
return ret;
}
public static List<Event> getAllEvents()
{
List<DataLayer.Event> dbEvents = DataApi.db.Event.ToList();
List<Event> returnEvents = new List<Event>();
foreach (DataLayer.Event oneEvent in dbEvents)
{
Event newEvent = new Event
{
ID = oneEvent.IDEvent,
userID = oneEvent.UserID,
projectID = oneEvent.ProjectID,
jobtypeID = oneEvent.JobTypeID,
taskID = oneEvent.TaskID,
ticketID = oneEvent.TicketID,
loccoID = oneEvent.LoccoID,
startTime = oneEvent.StartTime,
endTime = oneEvent.EndTime,
shiftFrom = oneEvent.ShiftFrom,
shiftTo = oneEvent.ShiftTo,
description = oneEvent.Description,
billable = oneEvent.Billable
};
returnEvents.Add(newEvent);
}
return returnEvents;
}
I tried displaying the events in fullcalendar:
$('#calendar').fullCalendar({
header: {
left: 'title',
center: '',
right: 'prev,next today basicDay,basicWeek,month',
},
//events: "/Calendar/GetEvents/", // not implemented
events: "#Url.Action("GetCalendarEvents/")",
and outputing the result to console:
console.log("#Url.Action("GetCalendarEvents/")");
but I get:
VM84 Index:83 /Calendar/GetCalendarEvents/
fullcalendar.min.js:6 Uncaught TypeError: Cannot read property 'hasTime' of undefined
It looks like you're missing some required fields. If you look at the documentation, title, start are required. Try setting these in the class to start with and build from that...
public static List<Event> getAllEvents()
{
List<DataLayer.Event> dbEvents = DataApi.db.Event.ToList();
List<Event> returnEvents = new List<Event>();
foreach (DataLayer.Event oneEvent in dbEvents)
{
Event newEvent = new Event
{
start = oneEvent.StartTime,
title = oneEvent.Description // you may need to add this to your Event class.
};
returnEvents.Add(newEvent);
}
return returnEvents;
}
Also, instead of using console to log the Json, use Fiddler or Chrome Advanced Tools

passing model and parameter with RedirectToAction

I want to send a string and a model (object) to another action.
var hSM = new HotelSearchModel();
hSM.CityID = CityID;
hSM.StartAt = StartAt;
hSM.EndAt = EndAt;
hSM.AdultCount = AdultCount;
hSM.ChildCount = ChildCount;
return RedirectToAction("Search", new { culture = culture, hotelSearchModel = hSM });
When I use the new keyword it sends null object, although I set the objects hSm property.
This is my Search action :
public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{
// ...
}
You can't send data with a RedirectAction.
That's because you're doing a 301 redirection and that goes back to the client.
What you need to is save it in TempData:
var hSM = new HotelSearchModel();
hSM.CityID = CityID;
hSM.StartAt = StartAt;
hSM.EndAt = EndAt;
hSM.AdultCount = AdultCount;
hSM.ChildCount=ChildCount;
TempData["myObj"] = new { culture = culture,hotelSearchModel = hSM };
return RedirectToAction("Search");
After that you can retrieve again from the TempData:
public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{
var obj = TempData["myObj"];
hotelSearchModel = obj.hotelSearchModel;
culture = obj.culture;
}

Resources