Call to undefined method stdClass::getModified() - php

Laravel v5.7.24
Laravel Auditing v8.0.4
PHP version 7.3.1
I've a specific problem related to package Laravel Auditing. Although I set the Model and everything like in documentation, the blade template is showing me an error Call to undefined method stdClass::getModified(). Thank you so much.
Here's my Model:
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
use OwenIt\Auditing\Contracts\Auditable;
class Post extends Model implements Auditable
{
use Searchable, \OwenIt\Auditing\Auditable;
protected $fillable = [...];
protected $auditExclude = [...];
public function user()
{
return $this->belongsTo('App\User');
}
}
Blade view:
<ul>
#forelse ($audits as $audit)
<li>
#foreach ($audit->getModified() as $attribute => $modified)
<ul>
<li>#lang('article.'.$audit->event.'.modified.'.$attribute, $modified)</li>
</ul>
#endforeach
</li>
#empty
<p>#lang('article.unavailable_audits')</p>
#endforelse
</ul>

Given that the error message (Call to undefined method stdClass::getModified()) refers to stdClass and not Audit, I'll take a wild guess and presume you're doing something like DB::table('audits')->where('auditable_type', Post::class)->get() to fetch the audits, which returns the results as POPO, not Audit instances.
Try this instead: Audit::where('auditable_type', Post::class)->get()

Related

Cannot use laravel relationship property in blade view

EDIT: Problem solved by adding local key in the model relation.
Question:
I am trying to use a property from model relationship {{$item->items->item_name}}, but it says Attempt to read property "item_name" on null.
However, when I am trying to {{dd($item->items->item_name)}} it returns a string "Old Boots.
Why does it happen? The value is definitely there but I cant echo it...
UserItems table: id | user_id | item_id
UserItem Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserItem extends Model
{
use HasFactory;
public function items()
{
return $this->hasOne(Item::class, 'id');
}
}
Item table structure: id | item_name
Item Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
use HasFactory;
}
Controller function:
public function heroView() :View
{
return view('hero', [
'userItems' => UserItem::with('items')->where('user_id', Auth::id())->get()
]);
}
View:
<table>
#foreach ($userItems as $item)
<tr>
<td>{{$item->items->item_name}}</td>
</tr>
#endforeach
</table>
In view {{dd($item)}}:
You did not show your db, so I am just guessing with the data you shared here.
First of all if there is one item for each user item, you need to change items name to "item".
And there is something else too. You need to set inverse relationship to. I mean you have to add this to your item model. If it's a one to one relationship read this for learning about inverse relationships.
One to one inverse relationship(laravel document)
And at last, please remove "with" method. You do not need it laravel will figure out the relationship by itself.
Said all the possibilities. Hope to be helpful <3
most likely reason is that one of your userItem does not have an item.
dd appears to work because it stops on the first iteration of the loop, but your missing item could be missing from userItem 4 for instance.
Whenever I use an arrow twice when accessing a relationship, I always code defensively and put in a null-coalesce operator to catch the situation where a relation is missing.
So you could prove this with code like;
<table>
#foreach ($userItems as $item)
<tr>
<td>{{$item->items->item_name ?? "no item"}}</td>
</tr>
#endforeach
</table>
I finally made it work. There was local key missing in the model.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class UserItem extends Model
{
use HasFactory;
public function items()
{
return $this->hasOne(Item::class, 'id', 'item_id');
}
}

Laravel get object attribute if object id is known

How do I get the value from a object if the ID is known?
So, I got the house id, in the house model there is an user_id for every house like:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use stdClass;
use App\Service\ChangesetService;
class HouseProfile extends Model
{
protected $guarded = ['id', 'user_id'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Every user got an address (string)
I need the address and I got the house id and I'm working in a blade file in Laravel 5.5
If I understand correctly:
#if($house->user)
{{ $house->user->address }}
#endif
You should never run queries of put too much logic in you Blade files. Instead you should pass variables to them.
In your controller
$house = HouseProfile::findOrFail($houseId);
return view('your.view.name', [
'house' => $house
]);
In your blade file you can use #IndianCoding response, so
#if($house->user)
{{ $house->user->address }}
#endif

Issue querying laravel eloquent relationship

This is with reference to this question :
Laravel Eloquent One to Many relationship
I tried the suggested way, but couldn't resolve. Please help. Below is the changes i have done :
Earlier :
//Route for Restaurants Page
Route::get('/home/restaurants',function(){
$restaurants = DB::table('restaurants')->simplepaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
Changed as per suggestion :
Route::get('/home/restaurants',function(){
// $restaurants = DB::table('restaurants')->simplepaginate(3);
$restaurants = \App\Restaurant::simplePaginate(3);
return view('restaurants',['restaurants_data'=>$restaurants]);
});
In Restaurant model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Restaurant extends Model
{
public function offer(){
return $this->hasMany('Offer');
}
}
In view, now I am trying to access it by dumping the values.
<?php
var_dump($restaurants_data->offer);
?>
Error :
After doing dd()
Firstly, I would suggest changing your Offer Relationship to:
public function offers()
{
return $this->hasMany(Offer::class, 'restaurant_ID', 'id');
}
The above assumes that the Offer class and Restaurant class are in the same namespace. If they're not please add the correct namespace or import the Offer model in to the class.
Secondly, because you're paginating the results you will end up with a collection of Restaurant models (even if there is only one), so you will need to loop through them to get access to the offers for each model. I would also suggest eager loading the results e.g.
Route:
Route::get('/home/restaurants', function () {
$restaurants = \App\Restaurant::with('offers')->simplePaginate(3);
return view('restaurants', compact('restaurants'));
});
in your view:
#foreach($restaurants as $restaurant)
#foreach($restaurant->offers as $offer)
{!! dump($offer) !!}
#endforeach
#endforeach
{{ $restaurants->links() }}
Can you replace
$restaurants = \App\Restaurant::paginate(3); and amend the blade code to say
<?php
foreach($restraunts_data as $resturant) {
if(count($restaurant->offer) {
print_r($restaurant->offer);
}
}
?>
You are using the models incorrectly. You run no queries and you attempt to run a static method on the Restaurant class without selecting any restaurants. As far as I know is this not supported by Eloquent. If you look at the error message it complains that there are no property $offer.
Try to run some query, and the select the related Offer. This should work as expected.
For example:
$offers = \App\Restaurant::find(1)->offer;
This will return the many Offer relations for the Restaurant with ID 1.

Undefined variable laravel 4.1

I am trying to get data from database and pass values to controller. I am new at laravel and thats the first query. Here is my code:
class Cars extends Eloquent
{
}
FleetController.php
public function index()
{
$fleet = Cars::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
{{ $fleet }}
#stop
The problem is that it shows this at log
Next exception 'ErrorException' with message
'Undefined variable: fleet (View: C:\wamp\www\laravel\app\views\pages\home.blade.php)' in C:\wamp\www\laravel\app\storage\views\7da5cff457f71f3156f90053865b6cb1:2
Stack trace:
You should try using
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
Your '->with()' just flashes the variable to your session. You still need to retrieve it from there though.
Also, you should try creating a model with the same name as your table. If you were to create a model Car that extends Eloquent, it will automatically be linked to your Cars table. Laravel docs:
The lower-case, plural name of the class will be used as the table
name unless another name is explicitly specified.
This part is important as well:
Eloquent will also assume that each table has a primary key column
named 'id'.
Once you got that configured, you'll be able to get the description of a car by simple doing
Car::all()->first()->description;
See also: Laravel docs on eloquent
Update
What should work:
Car.php
class Car extends Eloquent{
//Let's try setting these manually. Make sure they are correct.
protected $table = 'cars';
protected primaryKey = 'id';
}
FleetController.php
public function index()
{
//You have to call the model here, so singular 'Car'.
$fleet = Car::all()->first()->Description;
return View::make('pages.home')->with('fleet', $fleet);
}
home.blade.php
#extends('layouts.default')
#section('content')
//You can use blade's #if as well:
#if(Session::has('fleet'))
{{Session::get('fleet')}}
#endif
#stop

Laravel: Eloquent all() not returning an array of objects

I'm trying to build a simple forum system.
I have a model called Category.php, where I define the table and extend Eloquent.
I have a CategoryController.php which is a resourceful controller, within the index() method, I am doing:
$categories = Category::all();
Which I assume should return an array of objects. This worked fine on a different project of mine.
However, when I try to run this through a foreach, nothing is echoed. I've tried renaming the controller and the model to ForumController and Form, respectively, and it's worked straight away.
Any ideas? Perhaps the Category name has been reserved by Laravel and is overriding my desired functionality?
CategoryController.php:
<?php
class CategoryController extends \BaseController {
protected $layout = 'master';
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
$categories = Category::all();
$this->layout->content = View::make('category.index', array('categories' => $categories));
}
Category.php (model):
<?php
class Category extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
}
Category/index.blade.php (view):
#section('content')
<ul>
#foreach ($categories as $category)
<li>{{ $category->name }}</li>
#endforeach
</ul>
#stop
My database is set up correctly. When I run $category = Category::find(1); it correctly returns the category with an id of 1, which I can use as an object.
You can iterate over Category::all();. Laravels Collection class implements the following interfaces:
ArrayAccess, ArrayableInterface, Countable, IteratorAggregate, JsonableInterface
Which means:
foreach(Category::all() as $category) {
var_dump($category);
}
Will work, the Eloquent\Collection that is returned extends the Support\Collection class, which implements the above interfaces.
Take a look at the Support\Collection class in Illuminate.
You're right, when returning multiple results, Eloquent returns a Collection (which is quite common practise among frameworks).
You can convert a Collection to other formats using methods like toArray() or toJson(); but you can also iterate through the count() of results using methods like fetch(), or fetch specific entries using get()
EDIT
While you can't iterate directly over the Collection, you can convert it to an iterable structure using the getIterator() method, which returns an SPL ArrayIterator object

Categories