Laravel : Log:info in repository not printing values from Input - laravel-4

New to Laravel, hence want to understand this.
Is Log::info() not allowed to print some of the information ?
It dies silently, hence wondering if this is some Laravel rule I've yet to learn..
My HTML form is of this kind :
<form>
<input type="hidden" name="val[name]">
<input type="hidden" name="val[address]">
</form>
My Ajax function just creates a formData and sends it to the backend.
$.ajax({
url : baseUrl + 'update/' + id,
type : 'POST',
data : new FormData(this),
contentType : false,
cache : false,
processData : false,
success : function(
}
});
My Controller
prints the /Input::get('val') without an issue.
My Repository
public function update user($id, $val)
{
Log::info('reached forward() in the repository');
$post = $this->findById($postID);
Log::info('Going to print the values now');
Log::info('Val : ', $val);
//Log::info('Post-ID : ', $id);
Log::info('-----------------');
Log::info('Extracting the VAL to regular variables');
$expected = [
'name' => '',
'address' => []
];
/**
* #var $name
* #var $address
*/
extract($val = array_merge($expected, $val)); // create $name & $address
Log::info('After extraction'); // Gets printed
if($name == 'Tim')
{
Log::info('Name entered is in fact Tim'); // This does get printed
}
Log::info('Name sent is : ', $name); // **This is never printed**
Log::info('Printed Name'); // **This is never printed**
}
Am I doing something wrong, or is Laravel's Log function not allowed to print them ?
BTW, I don't see any error in the laravel.log or the php error log.

No, there are no special rules about how logging works - it logs whatever string is passed as the first argument + the context array that might be passed as second argument.
Let's have a look at your code:
Log::info('Name entered is in fact Tim'); // This does get printed
Log::info('Name sent is : ', $name); // **This is never printed**
Log::info('Printed Name'); // **This is never printed**
The first line gets printed, because a string is passed to info() method.
The second call is invalid, as you're passing 2 string arguments. If you meant to concatenate Name sent is: and $name, you need to use a dot instead of comma:
Log::info('Name sent is : ' . $name); // Now this will get printed
The reason why the third line is not printed is because the second one causes PHP to crash because of invalid type of second argument. It expects an array, but it gets string.

Related

How can I get only data from a response and show it into a blade template in Laravel 8?

Controller code
public function add_employee(){
$covid_statuses = Http::get("http://localhost:8000/api/v1/covid/status");
$covid_statuses = json_decode($covid_statuses['data'],200);
// $covid_statuses = json_encode($covid_statuses['data'],200);
return view('admin.hr.os.employee.add_employee',compact('covid_statuses'));
// return view('admin.hr.os.employee.add_employee',[
// 'covid_statuses' => $covid_statuses,
// // 'covid_statuses' => json_decode($covid_statuses['data']),
// ]);
}
The main respone is like {"data":[{"id":1,"name":"1st dose completed"},{"id":2,"name":"2nd dose completed"}],"success":true,"status":200}
When I decode only data, and pass into blade and in blade I use to debug like #foreach($covid_statuses as $covid_status) {{$covid_status}} #endforeach
but I got
json_decode() expects parameter 1 to be string, array given
When I use encode then I got
Invalid argument supplied for foreach()
How Can I solve this issue?
You could use array_walk for that purpose. Try:
$covid_statuses = array_walk($covid_statuses['data'], function(&$item, &$id) {
$item = $item['name'];
$id = $item['id'];
});
Like this, the array will only contain the names of the covid cases, by it will have the same id as in the original request

Laravel return after post is null with stored procedure

I have store method with return like this :
return redirect()->route('hasil.transaksi', ["data" => $data]);
with the route like this :
ROUTE::GET('hasil-transaksi', [KasirRajalController::class, 'hasilTransaksi'])->name('hasil.transaksi');
And method return like this :
public function hasilTransaksi(Request $request)
{
$data["info"] = DB::select("EXEC spx_kasirirj_GetData
#sdata = 2,
#where = '" . $request->no_transaksi . "'
");
dd($data);
}
URL after store like this :
http://127.0.0.1:8000/hasil-transaksi?data%5B0%5D%5B%5D=0000260&data%5B0%5D%5Bno_transaksi%5D=KRJ22010001
I want to catch no_transaksi=KRJ22010001 to paste in the method return above. But i don't get it, the result is null.
enter image description here
Please, help?
Full dd($request) :
enter image description here
There are multiple things to review in your code:
return redirect()->route('hasil.transaksi', ["data" => $data]);
This will do a GET redirect, so the $data object will be added as GET parameter and encoded (from object to string). That is why your URL only parameter is "data" (http://127.0.0.1:8000/hasil-transaksi?data=) and then the encoded data.
Your decoded URL data looks like this data[0][]=0000260&data[0][no_transaksi]=KRJ22010001.
This format seems a bit strange, but I don't have enough code to confirm. You could do this (assuming you don't need your 0000260 parameter [that should be keyed]):
return redirect()->route('hasil.transaksi', ["no_transaksi" => $data[0]['no_transaksi']]);
This should generate a correct URL ?no_transaksi=xx and so $request->no_transaksi should work (that you should also sanitize).
#where = '" . $request->no_transaksi . "'
As #Joundill mentioned, this part of your raw query is opened to SQL injection. If you don't use Eloquent, Models or Requests, you should at least sanitize and validate the no_transaksi request param value.

How i can get the variable data as string like a dd() function in Laravel?

I need to get the request data but i cant get ip, fullUrl and others with all() method (this only print input values), but when i use "dd(request())" this show me all data (i need the data what is printed with dd method, but like a string to save, withour the exception who print this data). Im debbuging my app so i need to save every request data in a log file, something like:
\Log::debug($request)
So,
You can use:
\Log::debug($request->toString());
or alternatively you can use
\Log::debug((string) $request);
The Laravel Request object comes from Illuminate\Http\Request which extends Symfony\Component\HttpFoundation which exposes the following code:
public function __toString()
{
try {
$content = $this->getContent();
} catch (\LogicException $e) {
return trigger_error($e, E_USER_ERROR);
}
$cookieHeader = '';
$cookies = [];
foreach ($this->cookies as $k => $v) {
$cookies[] = $k.'='.$v;
}
if (!empty($cookies)) {
$cookieHeader = 'Cookie: '.implode('; ', $cookies)."\r\n";
}
return
sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
$this->headers.
$cookieHeader."\r\n".
$content;
}
__toString() is considered a magic method in PHP.
The __toString() method allows a class to decide how it will react
when it is treated like a string. For example, what echo $obj; will
print. This method must return a string, as otherwise a fatal
E_RECOVERABLE_ERROR level error is emitted.
You can read more about it in the official documentation.
I highly recommend to store just what you want from request data if you don't need all of them, however for both cases you can take a look at serialize and json_encode

Get the CSRF token in a test, "CSRF token is invalid" - functional ajax test

I'm trying to test an ajax request in Symfony2. I'm writing a unit test which is throwing the following error in my app/logs/test.log:
request.CRITICAL: Uncaught PHP Exception Twig_Error_Runtime:
"Impossible to access an attribute ("0") on a string variable
("The CSRF token is invalid. Please try to resubmit the form.")
in .../vendor/twig/twig/lib/Twig/Template.php:388
My code is fairly straight-forward.
public function testAjaxJsonResponse()
{
$form['post']['title'] = 'test title';
$form['post']['content'] = 'test content';
$form['post']['_token'] = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken();
$client->request('POST', '/path/to/ajax/', $form, array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
$response = $client->getResponse();
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $response->headers->get('Content-Type'));
}
The issue seems to be the CSRF token, I could disable it for the tests, but I don't really want to do that, I had it working by making 2 requests (the first one loads the page with the form, we grab the _token and make a second request using with XMLHttpRequest) - This obviously seems rather silly and inefficient!
Solution
We can generate our own CSRF token for our ajax request with:
$client->getContainer()->get('form.csrf_provider')->generateCsrfToken($intention);
Here the variable $intention refers to an array key set in your Form Type Options.
Add the intention
In your Form Type you will need to add the intention key. e.g:
# AcmeBundle\Form\Type\PostType.php
/**
* Additional fields (if you want to edit them), the values shown are the default
*
* 'csrf_protection' => true,
* 'csrf_field_name' => '_token', // This must match in your test
*
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\AcmeBundle\Entity\Post',
// a unique key to help generate the secret token
'intention' => 'post_type',
));
}
Read the documentation
Generate the CSRF Token in your Functional test
Now we have that intention, we can use it in our unit test to generate a valid CSRF token.
/**
* Test Ajax JSON Response with CSRF Token
* Example uses a `post` entity
*
* The PHP code returns `return new JsonResponse(true, 200);`
*/
public function testAjaxJsonResponse()
{
// Form fields (make sure they pass validation!)
$form['post']['title'] = 'test title';
$form['post']['content'] = 'test content';
// Create our CSRF token - with $intention = `post_type`
$csrfToken = $client->getContainer()->get('form.csrf_provider')->generateCsrfToken('post_type');
$form['post']['_token'] = $csrfToken; // Add it to your `csrf_field_name`
// Simulate the ajax request
$client->request('POST', '/path/to/ajax/', $form, array(), array(
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
// Test we get a valid JSON response
$response = $client->getResponse();
$this->assertSame(200, $client->getResponse()->getStatusCode());
$this->assertSame('application/json', $response->headers->get('Content-Type'));
// Assert the content
$this->assertEquals('true', $response->getContent());
$this->assertNotEmpty($client->getResponse()->getContent());
}
While this question is very old, it still pops up as first result on Google, so I'd though I'd update it with my findings using Symfony 5.4 / 6.x.
Short answer: use the result of your Form type's getBlockPrefix() method as the tokenId:
$csrfToken = self::getContainer()->get('security.csrf.token_manager')->getToken('your_blockprefix');
Long answer:
This is the place where Symfony creates the CSRF Token within it's form system:
https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Form/Extension/Csrf/Type/FormTypeCsrfExtension.php#L81
The tokenId will be determined in the following order:
the form type's option csrf_token_id if present
the form type's block prefix as returned by the getBlockPrefix() method if present (see documentation)
the Entity's class name, converted to lowercase with underscores (see source)
Since I didn't want to add the csrf_token_id option to every single Form Type, I wrote the following method to obtain the CSRF Token based on the fully qualified name of a Form Type:
protected function generateCSRFToken(string $formTypeFQN): string
{
$reflectionClass = new \ReflectionClass($formTypeFQN);
$constructor = $reflectionClass->getConstructor();
$args = [];
foreach ($constructor->getParameters() as $parameter) {
$args[] = $this->createMock($parameter->getType()->getName());
}
/** #var FormTypeInterface $instance */
$instance = $reflectionClass->newInstance(... $args);
return self::getContainer()->get('security.csrf.token_manager')->getToken($instance->getBlockPrefix());
}
It instantiates an object of the Form Type mocking every required constructor parameter and then creates a CSRF token based on the instance's block prefix.

I have a form. On

I have a form. When validation fails i redirect to the same page. "mobilepage1.blade.php"
But all my entries are all gone. I want all my entries to stay. Exept the password.
I redirect my page with View::make
return View::make('mobilepages.mobilepage1', array('errormessages' => 'errormessages'));
I use:
$input = Input::all();
to get the input.
All input
return Redirect::to('mobilepages')->withInput(Input::all());
Except password
return Redirect::to('mobilepages')->withInput(Input::except('password'));
Old Input
In your form view, use something like this for the inputs:
<?= Form::text('title', (Input::get('title') ?: NULL)); ?>
The (Input::get('title') ?: NULL) operator will return the previous title value if it was set and nothing if it wasn't set.
It should be done using something like this:
public formSubmitMethod() // Change formSubmitMethod with appropriate one
{
// This is the form submit handler
// Set rules and validate the inputs
$rules = array(...); // set rules here but there are other ways
$inputs = Input::except('_token'); // everything but _token
$validatior = Validator::make($input, $rules);
if($validatior->fails()) {
// Validation failed
return Redirect::back()->withInput()->withErrors($validatior);
}
else {
// Success
// Do whatever you want to do
}
}
In your form, use Input::old('fieldname'), something like this:
{{ Form::input('username', Input::old('fieldname')) }}
That's it, now if you redirect back for invalid user inputs then your form fields will be repopulated with old values. Don't use old() method in the password field. You can also access the error message for a field using something like {{ $errors->first('username') }}, so if this (username) field invalidated then the error message for this field will be printed out.
Also, notice that, to redirect back, I've use Redirect::back() not View::make(), it's (make) not for redirecting but for rendering a view to show it.

Resources