Alessandro Gustavo Alessandro Gustavo - 17 days ago 6
PHP Question

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

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

Answer

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.

Comments