skip to Main Content

Please l am working with array in laravel. I want a way to access some values and display them as forms fields in blade.php file.

This is the array :

$postData = array(
            'source_addr' => 'JJA ENT',

    'encoding' => 0,
            'schedule_time' => '',
            'message' => 'Hello World',
            'recipients' => 

   [array('recipient_id' =>       '1', 'dest_addr' => '233554463045'),   array('recipient_id' => '2', 'dest_addr' => '255700000011')]
        );

This is how I return the view in this controller :

    return     view('main',compact('postData'));

In the blade file

<body>
    {{$postData['message']}}

This output the value corresponding to the message in the array.

I now want a way to get the attributes of the "recipients" too but when I pass the recipients like the way I did to the message, it returned errors.

This is how I return the view in the controller

   return view('main',compact('postData'));

In the blade

<body>
    {{$postData['message']}}

2

Answers


  1. You can use foreach Loop to get array values in blade. Here is an example

    {{$postData['message']}}
    
    @foreach ($postData['recipients'] as $recipient)
        <input type="text" name="recipient_id[]" value="{{$recipient['recipient_id']}}">
        <input type="text" name="dest_addr[]" value="{{$recipient['dest_addr']}}">
    @endforeach
    
    Login or Signup to reply.
  2. You shouldn’t mix different array notations. You’ll only confuse yourself for no reason. array() was used to keep compatibility with very old PHP versions that are no longer maintained. You should use [ ] instead.

    $postData = [
        'source_addr' => 'JJA ENT',
        'encoding' => 0,
        'schedule_time' => '',
        'message' => 'Hello World',
        'recipients' => [
            [
                'recipient_id' => '1',
                'dest_addr' => '233554463045'
            ],
            [
                'recipient_id' => '2',
                'dest_addr' => '255700000011'
            ]
        ]
    ];
    
    return view('main', [
        'postData' => $postData
    ]);
    
    <p>Source Address: {{ $postData['source_addr'] }}</p>
    <p>Encoding: {{ $postData['encoding'] }}</p>
    <p>Schedule Time: {{ $postData['schedule_time'] }}</p>
    <p>Message: {{ $postData['message'] }}</p>
    <p>Recipients</p>
    <ul>
      @foreach ($postData['recipients'] as $recipient)
        <li>ID: {{ $recipient['recipient_id'] }}. Address: {{ $recipient['dest_addr'] }}</li>
      @endforeach
    </ul>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search