Trying to get property of non-object in Laravel 5.3 - php

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.

Related

Retrieving a cast array in Laravel 5.5?

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 }

Livewire Laravel - TypeError: Cannot read property 'getAttributeNames' of null

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

Fetch first image from foreign key table Laravel

Reference: Fetch first image from foreign key table but this time in Laravel.
I started playing with Laravel and I want to take first image from every post and show these in my blade.
$secondpost = DB::table('posts')
->orderBy('id', 'desc')
->skip(1)
->take(8)
->get();
foreach ($secondpost as $spost)
$secondph = DB::table('post_images')
->select('filename')
->where('post_id', $spost->id)
->limit(1)
->get()
->pluck('filename');
return view ('pages.index', compact('firstp', 'fph', 'secondpost', 'secondph'));
<div class="row">
#foreach ($secondpost as $secondp)
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
<div class="row">
#foreach ($secondph as $sph);
<img src="{{url($sph)}}" class="imgpost" alt="">
#endforeach
<div class="bottomleft">
<p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
<p class="ab-desc">{{$secondp->pret}} Eur</p>
</div>
</div>
</div>
#endforeach
</div>
This code load only one image for every img src. Post_id is foreign key for posts table id.
There are few things you need to confirm.
You have created models for the table like Post for posts table and PostImages for post_images table. If not, follow the documentation. https://laravel.com/docs/5.8/eloquent
You have created the hasMany relationship in your post model with post_images. Like:
In Post model.
/**
* Get the images for the post.
*/
public function images()
{
return $this->hasMany('App\PostImage');
}
Then change in your controller to use early loading, Like:
$secondpost = \App\Post::with("images")
->orderBy('id', 'desc')
->skip(1)
->take(8)
->get();
And now the view looks like:
<div class="row">
#foreach ($secondpost as $secondp)
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6 post-ab">
<div class="row">
#php
$image = $secondp->images->first();
#endphp
<img src="{{url($image->filename)}}" class="imgpost" alt="">
<div class="bottomleft">
<p class="ab-desc">{{$secondp->marca}} {{$secondp->model}}</p>
<p class="ab-desc">{{$secondp->pret}} Eur</p>
</div>
</div>
</div>
#endforeach
</div>
Solution: 2
You can create another relationship with hasOne to get a single image like:
// In your Post model.
/**
* Get the default image for post.
*/
public function default_image()
{
return $this->hasOne('App\PostImage')->orderBy("id");
}
Make change in controller to use ->with("default_image").
And in view you can just use like:
$secondp->default_image->filename

How can I get the values of an array?

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.

Errors when trying to display relational data

I've been following the Laracasts Project-Flyer and have come to an end of the current videos in the series. I have decided to go off and expand on the app myself.
I'm trying to display the latest 3 flyers ( or in my case, classifieds) on the home page, along with an image.
I have been able to pull the last 3 entries and display them fine on the home page, but I've been trying to follow the same approach of displaying the images on the classified page, for the images for each classified on the home page.
Here is my code I have used.
Classified Model snippet:
<?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class classified extends Model
{
...
public function photos()
{
return $this->hasMany('App\classified_photo');
}
...
public static function getLatestClassifeds()
{
return DB::table('classifieds')
->select('ad_title','description')
->orderBy('created_at','desc')
->take(3)
->get();
}
...
Home Page Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\classifiedRequest;
use App\Http\Controllers\Controller;
use App\classified;
use App\classified_photo;
class HomeController extends Controller
{
public function show()
{
$classifieds = classified::getLatestClassifeds();
return view('pages.home', compact('classifieds'));
}
}
Home View:
#foreach($classifieds as $classified)
<div class="col-xs-6 col-sm-4">
<div class="col-xs-12">
#if($classified->photos)
#foreach($classified->photos as $photo)
<img src="/{{$photo->thumbnail_path}}" class="img-responsive">
#endforeach
#endif
</div>
<div class="col-xs-12">
<div class="classified-desc">
<h2>{{$classified->ad_title}}</h2>
<p>{{$classified->description}}</p>
</div>
</div>
<div class="col-xs-12">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Left</button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default">Right</button>
</div>
</div>
</div>
</div>
#endforeach
This code returns this error when I try to view the home page:
Undefined property: stdClass::$photos (View: /var/www/html/barrys-bikes.dev/resources/views/pages/home.blade.php)
As I say, displaying the 3 classifieds works fine, its just this issue with trying to then pull an image for each one.
The problems is, because you using DB::table()... instead of Eloquent ORM. Do something like this:
public static function getLatestClassifeds()
{
return self::orderBy('created_at','desc')
->take(3)->get(['ad_title', 'description']);
}

Categories