I have Helper class in my project. I have different two tables and I wrote sample function for get all needed details user by id.
Code of function:
public static function user($ id){ $ data = ['id' => null, 'role' => null, 'name' => null, 'email' => null, 'photo' => null, 'user_id' => null]; if(User::find($ id) !== null){ $ student = Student::where('id_user', $ id)->get()->toJson(); $ university = University::where('user_id', $ id)->get()->toJson(); if(mb_strlen($ student) > 5){ $ student = json_decode($ student); $ student = $ student[0]; $ data = [ 'id' => $ student->id, 'role' => 'student', 'name' => $ student->name, 'email' => $ student->email, 'photo' => $ student->photo, 'user_id' => $ student->id_user, ]; } elseif (mb_strlen($ university) > 5) { $ university = json_decode($ university); $ university = $ university[0]; $ data = [ 'id' => $ university->id, 'role' => 'university', 'name' => $ university->university_name, 'email' => $ university->emp_email, 'photo' => $ university->logo, 'user_id' => $ university->user_id, ]; } $ data = json_decode(json_encode($ data)); return $ data; } $ data = json_decode(json_encode($ data)); return $ data; }
And using this function I will create functions for check user role for example is_student()
,is_university()
and is_admin()
using my user()
function. How can be shorted and optimized my user()
function code? Thanks for help.