0

I'm new to Laravel. I need to retrieve specific data from the database using the JSON decode. I am currently using $casts to my model to handle the JSON encode and decode.

This is my insert query with json encode:

$request->validate([
        'subject' => 'required|max:255',
        'concern' => 'required'
    ]);

    $issue = new Issue;
    $issue->subject = $request->subject;
    $issue->url = $request->url;
    $issue->details = $request->concern;
    $issue->created_by = $request->userid;
    $issue->user_data = $request->user_data; //field that use json encode
    $issue->status = 2; // 1 means draft
    $issue->email = $request->email;
    $issue->data = '';
    $issue->save();

The user_data contains {"id":37,"first_name":"Brian","middle_name":"","last_name":"Belen","email":"[email protected]","username":"BLB-Student1","avatar":"avatars\/20170623133042-49.png"}

This is my output:

{{$issue->user_data}}

What I need to retrieve is only the first_name, middle_name, and last_name. How am I supposed to achieve that? Thank you in ADVANCE!!!!!

2
  • when you are receiving all the user data? Commented Dec 16, 2019 at 4:22
  • if you have used model you can get specific details like Table::select('first_name','middle_name ')->where('id', 1)->get(); Commented Dec 16, 2019 at 4:22

2 Answers 2

1

As per the above code shown by you it will only insert data into the database.For retrieving data you can make use of Query Builder as i have written below and also you can check the docs

$users = DB::table('name of table')->select('first_name', 'middle_name', 'last_name')->get();

Sign up to request clarification or add additional context in comments.

Comments

1

I will recommend using Resources. It really very helpful laravel feature. Check it out. It is a reusable class. You call anywhere and anytime.

php artisan make:resource UserResource

Go to your the newly created class App/Http/Resources/UserResource.php and drfine the column you want to have in your response.

public function toArray($request) {
return [
  "first_name" => $this->first_name,
  "middle_name" => $this->middle_name,
  "last_name" => $this->last_name
 ]
}

Now is your controller you can use the UserResource like folow:

public function index()
{
    return UserResource::collection(User::all());
}

Or after inserting data you can return the newly added data(f_name, l_name...)

   $user = new User;
   $user->first_name= $request->first_name;
   $user->middle_name= $request->middle_name;
   $user->last_name= $request->last_name;
   $user->save();

   $user_data= new UserResource($user);
   return $user_data;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.