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?
$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.
Related
Hi I think I'm misunderstanding casts? Basically I am trying to display an already stored array back to my view and its not working, i have already stored the arrays and im just trying to retrieve them into plain text
I have a table:
> Games
>>id |
>>name |
>>mode
MyController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\Game;
use App\Mode;
class MyController extends Controller
{
public function gameView($id)
{
$game = Game::find($id);
return view('admin.game.view', ['game' => $game]);
}
}
My model Game.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Game extends Model
{
protected $casts = [
'mode' => 'array',
];
public function modes()
{
return $this->hasMany(Mode::class);
}
}
Finally my View view.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">View User's Teams & Manage</div>
<div class="panel-body">
<ul>
<li>{{$game->name}}</li>
<li>{{$game->mode}}</li>
<li>{{$game->size}}</li>
</ul>
</div>
</div>
</div>
</div>
</div>
#endsection
There are so many ways of printing an array, however, the simplest method is using the foreach loop.
#foreach ($game->mode as $mode)
<span>{{ $mode }}</span>
#endforeach
Or you can do something like {{ implode(", ", $game->mode) }} depending on your preference.
You are displaying the array like a string and there is the problem so you need to loop for the array of mode.
#for($i=0;$i<count($game->mode);$i++){ // here you print your result }
I'm fetching data from Ajax after sending a form. There is a listener that is setting the attribute to my component.
What I'm trying to achieve is to display my results after having submitted the form.
In the component, the model has been well retrieved but when I would like to display it to my component, I get an error.
directive_manager.js:26 Uncaught (in promise) TypeError: Cannot read property 'getAttributeNames' of null
at _default.value (directive_manager.js:26)
at new _default (directive_manager.js:6)
at new DOMElement (dom_element.js:12)
at Function.value (dom.js:36)
at Component.get (index.js:56)
at Component.value (index.js:272)
at Component.value (index.js:246)
at Component.value (index.js:182)
at Component.value (index.js:158)
at Connection.value (index.js:30)
index.blade.php
<div id="results-products" class="results-products">
<livewire:charts-products>
</div>
....
<script>
...
var product= fetchData(url);
window.livewire.emit('set:product', product)
...
</script>
charts-products.blade.php
<div>
#isset($product)
#foreach ( $product->category as $category)
<div class="card">
<div class="card-header">
<h4>Product category</h4>
</div>
</div>
#endforeach
#endisset
</div>
ChartsProducts.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Product;
class ChartsProducts extends Component
{
public $products;
protected $listeners = [
'set:product' => 'setProduct'
];
public function render()
{
return view('livewire.charts-products');
}
public function setProduct($product)
{
$this->product= Product::find($product);
//I have checked and the assigned variable is ok
}
}
The products is a model and has a relationship Category.
Is there something that I missed ?
This has to do with the way the dom-differ inside Livewire behaves. Try adding a key to the loop item
<div>
#isset($product)
#foreach ($product->category as $category)
<div class="card" wire:key="{{ $loop->index }}">
<div class="card-header">
<h4>Product category</h4>
</div>
</div>
#endforeach
#endisset
</div>
See the troubleshooting in the docs https://laravel-livewire.com/docs/troubleshooting
Also, change your public property from $products to $product
I am building a QA, and when i try to show a question, I am getting this error. FatalErrorException Call to a member function except() on null in web.php line 10
Here is the web.php code
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('questions', 'QuestionsController')->except('show');
Route::get('/questions/{slug}', 'QuestionsController#show')->name('questions.show');
in the QuestionsController.php file the show function is
public function show(Question $question)
{
$question->increment('views');
return view('questions.show', compact('question'));
}
in addition, here is the view part when the question is displayed
<div class="card">
<div class="card-header">
<div class="d-flex align-items-center">
<h>{{ $question->title }} </h1>
<div class="ml-auto">
Back to all Questions
</div>
</div>
</div>
<div class="card-body">
{{ !! $question->body_html !! }}
</div>
</div>
so if my question is clear, how can I get rid of this error? Thank you for your help, Sirs!
Try to below code:
Route::resource('questions', 'QuestionsController', ['except' => ['show']]);
i think so it is because you should use find() or something elese first.
for example you should find question by id or slug or anything, then you can increment the field you want.
for example:
$question = Question::find(5)->increment('views');
or
$question = Question::where('url', '=', 'some value')->increment('views');
Correct your route. by following this sample code. Here is the official document you can check it [https://laravel.com/docs/5.4/controllers#resource-controllers]
Route::resource('questions', 'QuestionsController')->except(['show']);
Route::get('/questions/{slug}', 'QuestionsController#show')->name('questions.show');
guys i am working on laravel project (i am beginner in laravel ) my role in this project is making the views and injecting the data ... while i am trying to inject Post in my view i got this error "Trying to get property of non-object " i am searching on the internet and some says that "may be the object returns null but i checked all the data comes from the object in the Controller and i found data by dd($post);"
here's the HomeController method that returns the post object
public function index()
{
$sliders = Slider::take(5)->get();
$post = Post::latest()->first();
$users = User::subscribed()->take(12)->get()->shuffle();
return view('frontend.pages.home2', compact('sliders', 'sliders', 'users', 'post'))->with('success',' success test');
}
and this is what i am trying to do in the view
#foreach($post as $pos)
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$pos->body_ar}}
</p>
#endforeach
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
some text here to be displayed
<br>
<button type="button" class=" btn btn-primary">more</button>
</p>
<img class="nlpimage img-responsive " src="images/nnn.jpg">
</div>
and here's the Post.php class
namespace App\Src;
use App\Core\Traits\LocaleTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Post extends Model
{
use Notifiable, LocaleTrait;
public $localeStrings = ['title', 'body'];
public $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
public function gallery()
{
return $this->morphMany(Gallery::class, 'galleryable');
}
}
and the post table in the DB
enter image description here
Simply remove the foreach, because you are just passing one post instance to the view:
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$post->body_ar}}
</p>
If you want to display more post, change to controller, to get more results (and use the foreach in your template, because now its an array):
$post = Post::latest()->take(3)->get();
$post = Post::latest()->first();
Reason: If the data returned is empty or mis-matched then alone you will be getting this error.
If you pass one row of data alone to the blade the foreach() seems to be an invalid option over there.
And that is the reason you will be getting this error over there.
Your blade will look like:
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
{{$post->body_ar}}
</p>
<p class="text-primary col-lg-4 col-md-4 sliderParagraph menuDirection">
some text here to be displayed
<br>
<button type="button" class=" btn btn-primary">more</button>
</p>
<img class="nlpimage img-responsive " src="images/nnn.jpg">
</div>
Note: For passing of single value over to the blade you must not use foreach(). If it an array of values you can use foreach to iterate and then print the value over there.
I have 2 actions functions in my controller and I want to pass variable to an other action function
This is my first function in my controller
public function newUserAction(Request $request)
{ .........
$url = $this->generateUrl('userBundle_new_user_reasonCodeAjaxView',
array('id' => $newUser->getCode(),
'countCode' => $countCode,));
return $this->redirect($url);
This my second funtion in my controller
public function userCodeAjaxViewAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$pc = $em->getRepository('UserBundle:Code')->find($id);
if($pc != null)
{
return $this->render('UserBundle:userCodeView.html.twig', array(
'pc' => $pc,
));
}
And my twif looks like this
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ pc.name|trans }}
{{countCode}}
</div>
</fieldset>
</div>
</div>
</div>
I am getting an error Variable "countCode" does not exist in...
Is there any idea how I can use a variable from a controller in a other controller?
You can not get a variable from another controller.
Every request creates only one controller instance.
What you can do is create a Service that you can call in the controller.
Something like that:
class CountUserService{
public function count(){
return 1; // count users here
}
}
And the in the controller do this:
$service = new CountUserService();
$data=['countCode' => $service->count()];
return $this->render('UserBundle:userCodeView.html.twig', $data);
You are using the same template scope for the two controllers, and this is not possible. If you are using two controllers to render two simple informations, why not simply returning a JSON and displaying it in a more global template using AJAX ?
Else a pure symfony solution would be to have a main template view.html.twig where you would put
<div class="">
<div class="panel panel-default step3-textarea top-arrow top-arrow">
<div class="panel-body">
<fieldset>
<div>
{{ render(controller("AppBundle:UserController:newUserAction")) }}
{{ render(controller("AppBundle:UserController:userCodeAjaxViewAction")) }}
</div>
</fieldset>
</div>
</div>
Given that then your two controller action templates would be simple {{ pc.name|trans }} and {{countCode}}.
Hope it helps you out !