How To Print Data To Debug In Laravel? print_r v/s var_dump
As a programmer, we need to debug the code before the actual launch. So, it’s important to print the data to debug in Laravel for this we can use print_r, var_dump, die, or dd.
Laravel Collection
Laravel collection provides the wrapper for working with arrays of data. To print this collection we use the dd() function which is combination of dump() and die().So, if you want to use dump() to print the data, you can use die() to halt the process. Otherwise, dd() can do the same.
Convert Laravel Collection into Array
var_dump() and print_r() will show the messy array of Laravel collection to solve this you can also convert Laravel collection into array and print with dd(), dump() or var_dump() and print_r().
Public function list(){ $data = task::all(); dd($data->toArray()); or dump($data->toArray()); die(); }
I prefer to use <pre> tag surround the php’s native function print_r() to prettify the array data.
Public function list(){ $data = task::all(); echo “<pre>”; print_r($data->toArray()); echo “</pre>”; die(); }
Public function list(){ $data = task::all(); echo “<pre>”; Var_dump ($data->toArray()); echo “</pre>”; die(); }
Difference between var_dump() and print_r()
The difference between var_dump() and print_r() is that var_dump() function displays very detailed and structured information about the array and it’s elements.
It shows the data-types for each element’s value whereas print_r() simply displays the array in a human-readable form without any extra information about the array.
The best use of var_dump() over print_r() is in the case of null value like print_r(null) will display nothing whereas var_dump(null) will display NULL which is very-very useful in debugging.Working with Ajax
If you are working with ajax you can return an error in json form and then can show data in console.log().
Public function listData(){ $data = task::all(); Return response()->json($data); }
You can also customize the Laravel error handling https://laravel.com/docs/5.8/errors
If you like this article, feel free to comment and share this article. Your every comment and share is valuable for me.
1 thought on “How To Print Data To Debug In Laravel? print_r v/s var_dump”