Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel returning a leading \n character on responses

Tags:

laravel

Every response from my Laravel application seems to be getting prepend with a \n character, even when all I return is a number.

It feels like I have to have introduced this as a bug, but I can't find anywhere where I might have done that. I see I have some other applications I've built in Laravel that have this as well (but others that don't) so after pulling my hair out I thought I'd check and see if this something others have experienced.

The issue is that I'm trying to return an ID and use it but it has this leading character. I could strip it client side, but would rather fix the root issue.

ETA: This route:

Route::get('/test', function(){
    return 'hello world';
});

Produces this response:

screen shot with extra line

It's not an issue for HTML of course, but when I try to assign it as an id, I'm getting "\n 234".

like image 920
cfkane Avatar asked Nov 17 '16 17:11

cfkane


People also ask

How do I return a response in laravel?

Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response.

Which method will automatically convert the array into appropriate JSON response?

The json method will automatically convert the array into appropriate json response.

What is JSON in laravel?

JSON in laravel is a minimum package that makes decoding and encoding to throw exceptions of errors instantly.


2 Answers

I ran into the same issue and fixed it with phpStorm's global regex search:

[\s\S]\<\?php

In the end I had a new line in the index.php before <?php like mentioned in the other comments

like image 173
Markus Avatar answered Sep 28 '22 08:09

Markus


First of all PHEWW! this is a bad issue to end up with.

This can happen when any of your files starting from index.php of public folder to the controller which throws the response. Any where if at all there is a <?php ?> with a new line in between

or

any file involved in route request and response starting with <?php is on any other line than line no.1

Check your

  1. public/index.php
  2. bootstrap/app.php
  3. config/app.php
  4. any other files under config folder
  5. routes/web.php or routes/api.php
  6. app/Http/Controllers/YourController.php

I feel checking these must fix your issue. if not comment below lets discuss!

like image 32
BlackBurn027 Avatar answered Sep 28 '22 08:09

BlackBurn027