46

I go this error:

htmlspecialchars() expects parameter 1 to be string, object given

I'm using in controller:

$data = '{"pr":{"code":"1"},"ac":[[{"icon":"web","action":"link","url":"asd"}]]}'
$newData = json_decode($data);

And i send it to the view as array: 'data' => $newData And when i try to use $data into the view, it give me that error

Tried already to use $data->ac OR $data['ac'] but still the same... Some help, please?

Kiddo
  • 913
  • 2
  • 9
  • 13

5 Answers5

48

When you use a blade echo {{ $data }} it will automatically escape the output. It can only escape strings. In your data $data->ac is an array and $data is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }} (not sure why you have two nested arrays but I'm just following your data structure).

@foreach($data->ac['0'] as $link)
    <a href="{{ $link['url'] }}">This is a link</a>
@endforeach
jfadich
  • 6,110
  • 2
  • 20
  • 31
19

if you real intention is to send the full array from the html to the controller, you can use the following code:

from the blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 

in controller

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or
    
    return view('quotation')->with('quotation',json_decode($req->quotation))


}
Hernan Humaña
  • 433
  • 5
  • 18
8

You could use serialize

<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">

But best way in this case use the json_encode method in your blade and json_decode in controller.

brass monkey
  • 5,841
  • 10
  • 36
  • 61
Ehab Elzeny
  • 234
  • 4
  • 6
4

This is the proper way to access data in laravel :

@foreach($data-> ac as $link) 

   {{$link->url}}

@endforeach
Mostafa Norzade
  • 1,578
  • 5
  • 24
  • 40
1

Try use in your collection the json_encode().

https://www.php.net/manual/pt_BR/function.json-encode.php

public static function getTeamMemberInto($user_id){
    
    $team = DB::table('members_team')
                ->join('teams', 'teams.id', '=', 'members_team.teams_id')
                ->join('employees', 'employees.id', '=', 'teams.leader_employees_id')
                ->where('members_team.employees_id', '=', $user_id)
                ->select('*')->first();
    // dd($team);
    if($team){
        return json_encode($team, true);
    }else{
        return false;
    }
                        
}
Sven Eberth
  • 3,057
  • 12
  • 24
  • 29