How to display data to view from db after insertion? [L5.2] - json

what I am trying to do here is after the insertion I want to display the data in the same page without refreshing the page
ROUTES
Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
//there's {bookId} cause of this http://localhost:8000/viewBook/1
CONTROLLER
public function insertcomment(Request $request)
{
$commenter = Auth::user()->id;
$comments = new Comments;
$comments->comment = $request->input('mycomment');
$comments->commenter = $commenter;
$comments->save(); //insert success
//getting the data
$data=DB::table('comments')
->select('comment')
->get();
return response()->json($data,true);
}

You don't need to get the data from DB again, just return inserted Comment object:
$commenter = Auth::user()->id;
$comment = new Comments;
$comment->comment = $request->input('mycomment');
$comment->commenter = $commenter;
$comment->save(); //insert success
return response()->json($comment, true);

In your situation.
In http://localhost:8000/viewBook/1. You should send a AJAX request to Route::post('viewBook/{bookId}', 'CommentsController#insertcomment');
Then get response from server for append to current comments HTML section. The response like #Alexey Mezenin answer

Related

Why does Laravel redirect to a wrong id after DB::listen?

I would like to store every query I run inside my application. To do that, I've created a "loggers" table, a Logger modal and this function inside my boot AppServiceProvider
DB::listen(function($query) {
$logger = new Logger;
$logger->query = str_replace('"', '', $query->sql);
$logger->bindings = json_encode($query->bindings);
$logger->created_at = Carbon::now();
$logger->save();
});
Well, anytime I run an insert query, Laravel returns the loggers table ID instead of the model last inserted ID.
Why on earth does this happen?
public function store(CycleRequest $request) {
$appointment = new Appointment;
$appointment-> ... same data ...
$appointment->save();
if ( ! $errors ) ){
$msg['redirect'] = route('appointments.edit', $appointment);
// The page redirects to last logger id
}
}
I think you want to do triggers so I recommend use events for this, o maybe you can take the structure of you table "loggers" and do two differents querys each time that you do querys.
After searching a lot, I found a solution creating a Middleware. Hope this may help someone else.
I've created a QueryLogMiddleware and registered in 'web' middleware, but you may put it everywhere you want:
public function handle($request, Closure $next)
{
\DB::enableQueryLog();
return $next($request);
}
public function terminate($request, $response)
{
$queries = \DB::getQueryLog();
foreach ($queries as $query)
{
// Save $query to the database
// $query["query"]
// $query["bindings"]
...
}
\DB::disableQueryLog();
\DB::flushQueryLog();
}

How to add new parameters to my URL - Laravel?

I need your help. So, I need to add more details on my URL. But what I did doesn't working. I need to add id of news on my link. Now, my link is like that : www.website.com/news/my-news-title, but it should be like that : www.website.com/news/88/my-news-title.
Here is my route:
Route::get('news/{id}/{slug}', 'ModelController#newsSingle');
Here is my view link:
Here is my controller:
public function newsSingle($slug, $id)
{
// return $slug;
$data = $this->data;
$data['news'] = News::with('category_name','news_image','models','creative')->where('slug','=',$slug)->orWhere('id','=',$id)->first();
if(count($data['news']) == 0)
{
abort(404);
}
updatNewsView($data['news']['id']);
// $displayitem = DisplayItem::where('slug','=',url('news'))->first();
// $data['page'] = $displayitem;
$data['title'] = $data['news']->title;
$data['breadcrumb'] = $data['news']->title;
// $data['menu'] = $tag->title;
$data['metadescription'] = $data['news']->metadescription;
$data['metatitle'] = $data['news']->metatitle;
// $data['blogs'] = $tag->blog;
return view('news.single_news',$data);
}
Now, the link is good, but when I'm trying to access it I get 404 error .
Your params are switched around in your controller. You have id/slug in your route but $slug, $id in your controller action.
Changing the following should work:
Controller:
public function newsSingle($id, $slug)
View:
Or use the named routes from mrhn's answer.
Your Url generation seems wrong, usually you would do named routes.
Route::get('news/{id}/{slug}', 'ModelController#newsSingle')->name('news');
Generate your url like this in the blade, by using the route helper that will return the url.

How to process incoming JSON data from connected IoT device

I need some support with a personal project Im working on. I have a connected device which sends JSON data at a defined interval (every 1 min / 5 min/ 15 mins etc) to a specific IP address on port 8080.
The JSON that is sent is in following format:
{
"MeterSN": “1234”,
"Status": ###,
“Variable1”: “###”,
"Variable2”: “###”,
"Variable3”: ###
}
I have started building a PHP Rest API to process this data but am somehow not able to save the to mySQL.
Here is what I have so far:
meterdata.php
class MeterDataInput{
private $conn;
private $table_name = "meterdata";
public $MeterSN;
public $StatusA;
public $Variable1;
public $Variable2;
public $Variable3;
public function __construct($db){
$this->conn = $db;
}
}
function createMeterRecord(){
$query = "INSERT INTO
" . $this->table_name . "
SET
MeterSN=:MeterSN, Status=:Status, Variable1=:Variable1, Variable2=:Variable2, Variable3=:Variable3";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->MeterSN=htmlspecialchars(strip_tags($this->MeterSN));
$this->Status=htmlspecialchars(strip_tags($this->Status));
$this->Variable1=htmlspecialchars(strip_tags($this->Variable1));
$this->Variable2=htmlspecialchars(strip_tags($this->Variable2));
$this->Variable3=htmlspecialchars(strip_tags($this->Variable3));
// bind values
$stmt->bindParam(":MeterSN", $this->MeterSN);
$stmt->bindParam(":Status", $this->Status);
$stmt->bindParam(":Variable1", $this->Variable1);
$stmt->bindParam(":Variable2", $this->Variable2);
$stmt->bindParam(":Variable3", $this->Variable3);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
index.php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once 'config/db.php';
// instantiate MeterData object
include_once 'objects/meterdata.php';
$database = new Database();
$db = $database->getConnection();
$meterdata = new MeterDataInput($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(!empty($data->MeterSN)){
// set product property values
$meterdata->MeterSN = $data->MeterSN;
$meterdata->Status = $data->Status;
$meterdata->Variable1 = $data->Variable1;
$meterdata->Variable2 = $data->Variable2;
$meterdata->Variable3 = $data->Variable3;
// create the meter data entry
if($meterdata->createMeterRecord()){
// set response code - 201 created
http_response_code(201);
// update the status
echo json_encode(array("message" => "Data record was added"));
}
// if unable to create the record
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to add record."));
}
}
// data is incomplete
else{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to create data record. Data is incomplete."));
}
Obviously i also have config.php and db.php
I am not sure where i am going wrong, however I am not able to see the records popupate within mySQL.

Yii2 Login Only For One Page

I have been attempting to implement an OpenID log-in with Yii2 today, and for the most part it has worked. Below is code from my controller, with the action 'Register' running through, and outputting the user->identity->username, but when I, say, redirect this action back to any page on the site, the logged in user is essentially forgotten. I can return to my Register action and have the user logged in.
Help would be appreciated. Thank you.
public function actionRegister()
{
require ('../views/site/steamauth/userInfo.php');
$localId = $_SESSION['steam_steamid'];
$foundUser = User::findOne(['steamid' => $localId]);
if(isset($foundUser))
{
Yii::$app->user->login($foundUser);
var_dump($foundUser);
echo Yii::$app->user->identity->username;
} elseif(!isset($foundUser)) {
$db = new User();
$db->steamid = $_SESSION['steam_steamid'];
$db->username = $_SESSION['steam_personaname'];
$db->visstate = $_SESSION['steam_communityvisibilitystate'];
$db->profile = $_SESSION['steam_profileurl'];
$db->avs = $_SESSION['steam_avatar'];
$db->avm = $_SESSION['steam_avatarmedium'];
$db->avf = $_SESSION['steam_avatarfull'];
$db->persstate = $_SESSION['steam_personastate'];
$db->save();
$foundUser = User::findOne(['steamid' => $localId]);
Yii::$app->user->login($foundUser);
return $this->goHome();
}
}
/**
Ah. After scouring Stackoverflow I found it.
The standard model function findIdentity
return isset(self::$usrs[$id]) ? new static(self::$usrs[$id]) : null;
must be change to reflect the new table of
return User::findOne($id);

How to avoid the instruction "return" inside a function in Symfony2?

I would like to know how to avoid the instruction "return" inside a function in Symfony2. In other words how can I make a void function which doesn't return anything. In fact I have tried that for a long time but every time I run the code I did I see this error message: "The controller must return a response" ... By the way, this is the code that I have:
public function AddeventsgroupeAction(Request $request) {
$eventg = new eventsgroupe();
$form = $this->createForm(new eventsgroupeType(), $eventg);
$em = $this->getDoctrine()->getManager();
$securityContext = $this->get('security.context');
$token = $securityContext->getToken();
$user = $token->getUser();
$id = $user->getId();
$groupe=$this->getRequest('groupe');
$idg = intval($groupe->attributes->get('id'));
$qb = $em->createQueryBuilder();
$qb->select('l')
->from('IkprojGroupeBundle:Groupe', 'l')
->from('IkprojGroupeBundle:eventsgroupe', 'e')
->where(' l.id = :g and e.idGroupe = l.idAdmin and l.id = e.idEventGroupe');
$qb->setParameter("g", $idg);
$query = $qb->getQuery();
$res = $query->getResult();
$rows = array();
foreach ($res as $obj) {
$rows[] = array(
'id' => $obj->getId());
}
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isValid()) {
$eventg-> setIdGroupe($id);
$eventg-> setIdEventGroupe($idg);
$em->persist($eventg);
$em->flush();
return $moslem="yes";
}
} else {
return $this->render('IkprojGroupeBundle:GroupeEvents:Addeventgroupe.html.twig', array(
'groupe' => $rows,
'event' => $eventg,
'form' => $form->createView(),
));
}
}
How can I replace the instruction : return $moslem="yes"; in order to not return anything??...Is that possible??
To answer your basic question, a simple return will return a void from your function.
The "controller must return a response" message actually comes from the request handler. You need to tell the request handler what you want it to do. There is no default page so a void return will trigger the error.
In most cases, after successfully processing a posted form you will want to return a redirect response.
Something like:
$form->handleRequest($request);
if ($form->isValid()) {
...
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
I should point out that your form code seems to be from S2.1 or older. It's unnecessarily complicated. You should be using at least 2.3. Make sure you are looking at the correct version of the documentation. Hint: the isValid() takes care of the POST check.
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
It's also worth while to understand the request/response workflow.
http://symfony.com/doc/current/book/http_fundamentals.html
Digging into the code can also help in understanding where the error message is coming from:
Symfony\Component\HttpKernel\HttpKernel#handleRaw($request)
Simple, delete the else statement and if $request->isMethod('POST') or $form->isValid() returns false the code inside will not be executed then the script return the default view.
EDIT: you can also make a redirect with a flash message where needed like this:
$this->get('session')->getFlashBag()->add('success', 'your success message');
return $this->redirect($this->generateUrl('your_route'));
Remember to add support for flash message in your view looking at the Symfony2 docs