How to print out value on controller Laravel? - php

I'm beginner on Laravel...
How to debug some value on controller in Laravel, result can show to console like syntax console.log() on javascript?
example controller function :
class TestMeController extends Controller {
public function __construct()
{
$this->middleware('jsonify');
}
public function callMe($id)
{
$params = Request::all();
console.log($id); <== how to write code on Laravel?
}
}

In Laravel use dd($id) or if you don't want to halt the execution, you can use dump($var).
You can still always use PHP's native functions like var_dump, die and print_r.

You can Use these several methods for printing in Laravel.
1. dump($var)
2. dd($id)
3. var_dump($var)
4. die($var)
5. print_r($var)

dd($var) is great because it stops the program after it runs so by moving it around you get a good sense of which line of code is causing an error.

In my case I am using laravel 7 with blade templates and to test my controller
(MVC ARCHITECHTURE)
I usually use:
return dd($variable)
or even just
return $variable

If you just want to see the data
$events = new Event();
echo "<pre>";
print_r($events->all()->toArray());
echo "</pre>";
die;

Use a return response with json:
return response()->json($dataVar, status_code);
instead console.log();
return response()->json($id, 200);

Related

PHP serialize() is not properly serializing stdClass object

I have an application running on Google App Engine (using PHP 5.5.38), and I'm using a Laravel package for caching query results.
This worked well for a similar project, but for this one, I get errors such as, "unserialize(): Error at offset 14 of 860 bytes" (the numbers vary, depending on what was serialized.)
The error occurs in a class that has only these two functions:
public function encode($data){
return serialize($data);
}
public function decode($data){
return unserialize($data);
}
I found that when testing the app locally, everything works correctly, and the serialized data looks something like this:
a:1:{i:0;O:8:"stdClass":27:{s:2:"id";i:2;s:10:"first_name";s:4:"Zach";...
But when I run it on App Engine with the same data, it returns this:
a:1:{i:0;O:8:"#*lass":27:{s:2:"id";i:2;s:10:"first_name";s:4:"Zach";...
It might not show here, but there are invisible characters next to the '*' (in notepad++, they show up as [ENQ] and [DLE]).
I believe that the call to unserialize() fails because the serialized data contains #*lass instead of stdClass, but I don't know what's causing it, or how to prevent it. I tried using str_replace, and it worked at first, but not for everything. I also made sure that PHP was using UTF-8 as the default charset.
EDIT: I modified the encode function to try to pinpoint the moment the trouble starts.
I now have:
public function encode($data)
{
$serialized = serialize($data);
try{
unserialize($serialized);
} catch (\Exception $ex) {
var_dump($serialized);
die;
}
return $serialized;
}
And when it's executed on the server, it outputs:
a:1:{i:0;O:8:"#*lass":27:{s:2:"id";i:2;s:10:"first_name";s:4:"Zach"; ...
So it seems like the problem starts with before anything is saved or unserialized.
Probably not an ideal fix, but this seems to work...
public function encode($data)
{
return serialize(json_decode(json_encode($data), true));
}
public function decode($data)
{
return json_decode(json_encode(unserialize($data)));
}
The problem seemed to come from serializing an array of stdClass objects, so I figured it would help to convert stdClass to associative arrays.
This works for me
$data = json_decode(json_encode($data), true);
$data_serialized = serialize($data);

print statement in symfony

I'm new with symfony and I'm looking for a a kind of "print statement". Before I was programming only with java so I could see and keep track of the code on my "console output" inside the IDE. Basically I was using print system out
What could be the equivalent to symfony. For example
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneById($id);
Could I do something like this:
echo $user, inside the controller? and see the result somewhere
Or I should allways render the $user:
return $this->render('FOSUserBundle::edit.html.twig', array(
'user' => $user,
'form' => $form->createView()
));
then I could only see the result on the edit.html
Is that the only way? (using render)
Later on, I would like to use PHPUnit but at the moment I want to start from the basics
Thank you!
Yes, you can:
public function fAction(Request $request){
// ...
$user = $this->getDoctrine()
->getRepository('AppBundle:User')
->findOneById($id);
var_dump($user); exit;
// or ...
exit(\Doctrine\Common\Util\Debug::dump($user));
// or if you've installed VarDumper component (see below):
dump($user, $anotherUser, $request);
exit;
// ...
}
Try installing VarDumper component, and use its dump() function.
There are many ways to print a variable for debugging purposes in the middle of the script.
One of them is to use var_dump().
Following code will dump your variable and terminate the script.
var_dump($users);
die();

{"status":false,"error":"Unknown method"} error CodeIgniter RESTful API

<?php
include(APPPATH.'/libraries/REST_Controller.php');
class Quiz extends REST_Controller{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function user_get()
{
$this->load->model('Quizmodel');
$data = $this->Quizmodel->getAll();
$this->response($data, 200);
}
function restclient()
{
$this->load->library('rest', array(
'server' => 'http://localhost/CodeIg/index.php/quiz/'
));
$userr = $this->rest->get('user','','json');
echo $userr;
}
}
?>
I am able to get JSON output if I type http://localhost/CodeIg/index.php/quiz/user in my browser, however if I type http://localhost/CodeIg/index.php/quiz/restclient it gives this error: {"status":false,"error":"Unknown method"}
I tried changing get to post but still the same error.
I referred this page https://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter--net-8814 to do it.
You pinged me on GitHub, even though I haven't used or even thought about this code in at least 4 years.
https://github.com/chriskacerguis/codeigniter-restserver/blob/d19dc77f03521c7a725a4555407e1e4e7a85f6e1/application/libraries/REST_Controller.php#L680
This is where that error is being triggered. Throw a few breakpoints in there or var_dump()'s until you see what is causing the trouble.
You probably want to get off CodeIgniter though, and use something more actively maintained like SlimPHP or Lumen.
firstly I want as you have loaded rest api and created your controller quiz as an api to call , where you can only create your functions like user_get or restclient_get and access them the same manner you are doing.Just change you function name restclient to restclient_get then it will call instead it is even not running at this moment.

Laravel dd() equivalent for Cake PHP

I would like to know if there is an equivalent method to laravel method dd() for Cake PHP.
If you don't know, dd() dump the given variable and end execution of the script.
Thanks you.
Try adding a prd() function into bootstrap.php
function prd($var)
{
pr($var);
die;
}
source: http://debuggable.com/posts/make-your-life-easier-with-these-five-cakephp-quicktips:48170ee5-0cc0-4815-af60-7c264834cda3
You could also add it to cakephp/app/Config/helpers.php
https://github.com/larapack/dd
Very straightforward to install via Composer.
Jus use dump($var);
After that you can stop the execution with exit;

Trying to debug a symfony app showing the list of all the functions called, debug_backtrace() doesn't fits me

im trying to debug a symfony app.
I've added a debug_backtrace() calling to this function below. It
outputs a list of functions called, but the save() function (that is
just before the debug_backtrace() calling) is not that list.. why? any other way to debug that shows more things, in this case the save() calling ?
protected function processForm(sfWebRequest $request, sfForm $form)
{
$form->bind($request->getParameter($form->getName()));
if ($form->isValid())
{
$sf_guard_user = $form->save();
var_dump(debug_backtrace());
die("fsdgsgsdf");
$this->redirect('guardausuario/edit?id='.$sf_guard_user-
>getId());
}
}
Regards
Javi
I've just got my target using
xdebug_start_trace('/tmp/foo');
$usuario = $form->save();
xdebug_stop_trace();
http://www.xdebug.org/docs/all_functions
Javi
Symfony's web developer bar has some great information.
What exactly are you trying to see? Somethings it is good to echo $form because it will reveal all of the fields and any hidden fields in the form. Also, remember to include [_csrf_token] in your View if you are writing a custom View.
And... Symfony and xDebug are a good combination.
In php.net (http://php.net/manual/es/function.debug-print-backtrace.php) bishop exposes this solution:
$e = new Exception();
$e->getTraceAsString();
It gives a short but concise response for all the functions being called. It perfectly suited my needs, so I can log what happened without being lost.

Categories