John Davidson

php - Convert NULL into empty string while getting response

0 comments
Message:


i just want how can we convert null into empty string while getting result from db.
For example


User::first();

In user table, roll number is null value. i want it to convert into empty string.



My Answer:
You can achieve this by using the `COALESCE` function in your query. Here's an example of how you can convert a NULL value to an empty string while getting the result from the database in Laravel:

php
$user = User::selectRaw('COALESCE(roll_number, "") as roll_number')->first();


In this query, we are using the `COALESCE` function to check if the `roll_number` column is NULL. If it is NULL, it will return an empty string instead. This way, you will get an empty string instead of NULL in the `roll_number` attribute of the `$user` object.

Rate this post

3 of 5 based on 8613 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us