donglu1472 2018-04-27 22:39
浏览 63
已采纳

如何获取数组的值?

I am trying to access the properties of an array from a view. A controller is passing the array to that view. For some reason am not able to access the the array properties.

Error Message:

Trying to get property 'message' of non-object (View: /path/to/file/message.blade.php)

View code + where error is occurring:

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">


            <div class="card">
                <div class="card-header">{{$message->title}}</div>

                <div class="card-body">
                    {{$message->message}}
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Controller code that is returning the above view:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;
use App\User;

class becomeorganiser extends Controller
{
    public function becomeorganiser(){
      $user = Auth::user();
      $user->organiser = 1;
      $user->save();
      $message = [];
      $message['title'] = 'Success!';
      $message['message'] = 'You are now an event organiser<br>You now have access the oragnisers control panel in your navigation bar!';

      return view('message', $message);
    }
}

If I do {{print_r($message)}} The contents is printed out. To be clear I cannot access either the title or message properties

What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • doulingna9420 2018-04-27 22:44
    关注

    $message is not an object, yet you are accessing it as one. It is an array as you have defined it as such in your controller ($message = [];), therefore you need to access it as such.

    So, it should be like this,

    <div class="card-header">{{ $message['title'] }}</div>    
    <div class="card-body">
          {{ $message['message'] }}
    </div>
    

    Hence, the error:

    Trying to get property 'message' of non-object (View: /path/to/file/message.blade.php)

    is completely valid.

    Reading Material

    array

    object

    Edit #1

    Regarding your new error,

    Illegal string offset 'title' (View:.....

    As per my comment and your update, you are using numeric keys yet the array has been defined as an associative array. Please read above again this time noticing how I am accessing the values from the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记