简体   繁体   中英

Get a specific value from a json data

I have the PagesController function that looks like this:

public function home(){
        if (\Session::has('user_id')){
            $posts = DB::table('posts')->get();
            $user = DB::table('users')->where('id', \Session::get('user_id'))->first();
            return view('home', compact('posts', 'user'));
        }else{
            return view('welcome');
        }
    }

And, in my view home.blade.php , when I print out the data using {{$user->user_json}} , I get:

{"id":6,"friends":[],"posts":[],"messages":[],"notifications":[],"pin":""}

So now, How do I get a specific value like the id of the user?

If you sent json, you have to decode in the blade and it will return an associative array as we passed true in the second parameter

$user_data = json_decode($user_json, true);

$json = json_decode($user->user_json, true);
{{$json['id']}} 

Or

$obj= json_decode($user->user_json);
$obj->id;

Try the above code it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM