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

如何获取数组的值?

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
    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.

    点赞 评论

相关推荐