Laravel Relation Query/Find - Trying to get property of non-object - php

I'm not able to fix this error when I tried associate category to transaction.
// TransactionController
$transactions = DB::table('transactions')
->where('status', 'false')
->orderBy('date','asc')
->get();
foreach($transactions as $data) {
$transaction = new Transaction();
$transaction->id = $data->id;
$transaction->category = Transaction::find($data->categories_id)->category;
$transaction->description = $data->description;
}
The error occurs at time:
ErrorException in TransactionController.php line 80:
Trying to get property of non-object
Line 80: $transaction->category = Transaction::find($data->categories_id)->category;
But, if I test my code with die, that's result:
die(Transaction::find($data->categories_id)->category()->first());
{"id":1,"users_id":1,"description":"Alimenta\u00e7\u00e3o","created_at":"2016-11-15 20:31:11","updated_at":"2016-11-15 20:31:11"}
// Transaction Model
class Transaction extends Model
{
public function category(){
return $this->hasOne('App\Category','id');
}
[]'s

You are getting that error as one or multiple $data->categories_id are not matching the id on the transactions table.
Note:
It's not a good practice to find a model and call a function on it on the same line as you have done.
Transaction::find($data->categories_id)->category;
Because, you never know what id will be passed as argument to find().
Better go for findOrFail().
$tran = Transaction::findOrFail($data->categories_id);
$cat = $tran->category;
The findOrFail() function will throw a ModelNotFoundException whenever the id doesn't match in the transactions table. This exception can be easily handled by try...catch block.

Related

Can't access object field after eager loading in Laravel 8

When I'm trying to eager load my Model with relation like that:
$plants = Plant::with('history')
->get()
->where('user_id', auth()->id());
I want to modify those extracted dates with my function like that:
foreach ($plants as $plant) {
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
$plant->fertilized_at = self::getDateForHumans($plant->history->fertilized_at);
}
I get this kind of error:
ErrorException
Trying to get property 'watered_at' of non-object
but if I try to debug it by dd() function i get a positive result
dd(self::getDateForHumans($plant->history->watered_at));
dd() result
Does anybody know how to fix it or what is the workaround?
seems your history has no watered_at member, so it comes to this error.
Check first if you can access this member with
if(isset($plant->history->watered_at)){
$plant->watered_at = self::getDateForHumans($plant->history->watered_at);
}

PHP Traits "Method does not exist"

I am using laravel-comment to enable Users to comment on each other. Therefor, I need to use both the Commentable and the CanComment trait. But when I use them together, I get an error.
User uses it like this:
use Commentable, CanComment {
Commentable::comments insteadof CanComment;
}
And I am trying to seed the comments like this:
foreach (User::all() as $user) {
$receiver = User::where('id', '!=', $user->id)->inRandomOrder()->get();
$user->comment($receiver, $faker->text(100), 3);
}
Even though the CanComment trait has a method called getCanBeRated, I get an error saying that it doesn't. Why is this happening?
You're getting this error because you're trying to use this method on collection and not on User object. Use first() instead of get() to get an object instead of collection:
$receiver = User::where('id', '!=', $user->id)->inRandomOrder()->first();

paginate() function throwing exception - PDOException SQLSTATE[HY093]: Invalid parameter number for in Laravel

I am using below code to fetch records from database in Laravel
$products = new Product();
$products = $products->orderBy('id', 'DESC')->paginate(10);
But it's throwing exception
PDOException SQLSTATE[HY093]: Invalid parameter number
It's also showing below error:
Illuminate\Database\QueryException SQLSTATE[HY093]: Invalid parameter
number (SQL: select count(*) as aggregate from 'tbl_products' where
'tbl_products'.'deleted_at' is null and 'category_id' = 10 and created_at
between and ?)
I tried to find a solution which is already posted here but didn't work for me.
Before executing above code I've written code in a function and I think that code is affecting.
$timeframe = Input::get('daterange');
$products = $products->whereBetween('created_at', $timeframe);
$products = new Product();
$products = $products->orderBy('id', 'DESC')->paginate(10);
This does not fetch records - you are creating a new, empty product object, and then trying to query it.
To retrieve all Products and order and paginate them, try this:
$products = Product::orderBy('id', 'DESC')->paginate(10);

Laravel whereHas eloqvent relation

i am trying to get object from table orders with related attributes from table order_status_history. From table order_status_history, i need only last record with status 'Reviewing', so i use sort asc by field created_at. My code so far is , but i get error.
$orders = Order::GetOrderHistoryReviewing()->get();
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing')->orderBy('created_at','desc')->first();
});
}
i need one object with relation from second table
this is my error
[2016-07-27 08:37:26] dev.ERROR: exception 'PDOException' with message 'SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "orders"
LINE 1: ...ries" where "order_status_histories"."order_id" = "orders"."...
From your question, you're apparently trying to create a scope that returns orders with status, 'Reviewing' and sorts the results in descending order.
You need to remove the first() call from the $q subquery and move orderBy to the end of your $query. Your code should look like.
public function scopeGetOrderHistoryReviewing($query)
{
return $query->whereHas('statusHistory', function($q) {
$q->where('status', 'Reviewing');
})->orderBy('created_at','desc');
}
Then you can do:
$orders = Order::GetOrderHistoryReviewing()->get();
//OR to get the first record
$first_order = Order::GetOrderHistoryReviewing()->first();

Kohana 3 find_all returns model instead of result set object

I wrote in my controller a conditional filter working like this:
$this->_view = View::factory('crud/index')
->bind('collection', $collection);
$collection = ORM::factory($this->_model);
if (Request::current()->method() === Request::POST)
{
foreach (Request::current()->post('filter') as $field => $value)
{
$collection->where($field, '=', $value);
}
}
$collection->find_all();
And in the view I have a conditional to display a message if there are no filtered results or rows in database.
<?php if ( ! $collection->count()): ?>
This gives me an exception:
Kohana_Exception [ 0 ]: Invalid method count called in Model_Product
The problem is that before adding the filter, my controller action was:
$this->_view = View::factory('crud/index')
->bind('collection', $collection);
$collection = ORM::factory($this->_model)->find_all();
And $collection->count() worked just fine in the view. Why is the ORM find_all() method returning a model even if I don't post, even if the code is not entering the conditional? Just breaking $collection = ORM::factory($this->_model)->find_all(); into $collection = ORM::factory($this->_model); and $collection->find_all(); breaks the whole thing. Why is that strange behavior?
Thanks.
Try doing this:
$collection = $collection->find_all();
find_all() doesn't save the query results in the ORM object, you need to save it in a variable.

Categories