mardi 15 mars 2016

Laravel 5.2 has many relationship - can't access fields

I have read the documentation about eloquent relationship and different articles online about it. but it seems I'm getting a hard time accessing the fields for my table's relationship. Please advice.

User->hasMany BuyRequest

User table columns: id, userid (int), name

BuyRequest table columns: id, buyrequest_id, userid (int)

Here code of my User Model,

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\BuyRequest;
class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','userid',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function buyRequest(){
        return $this->hasMany(BuyRequest::class,'userid','userid');
    }

}

code of my buyRequest Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use App\User;
class BuyRequest extends Model
{
    //
    protected $table = 'buyrequest';

    protected $fillable = [
        'buyrequest_id'
    ];

}

Controller class where I'm accessing the variable

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\ProductPostRequest;
use App\Products;
use Illuminate\Support\Facades\DB;
use App\BuyRequest;
use App\Http\Requests\RFQRequest;
use App\ProductCategory;

class TaskController extends Controller
{

    public function show(Request $request){

        $user = new User();
        $buyrequest = $user->buyRequest();

        dump($buyrequest->getResults());
    }

}

Output:

Collection {#241 ▼
  #items: []
}

I have zero items on my collection, am I accessing the buyrequest properly? please help.

I already tried the one in laravel documentation, please see below.

$buyrequest1 = User::find(1)->buyrequest;

        foreach ($buyrequest1 as $br) {
            dump($br->title);
        }

and I get this output:

Trying to get property of non-object

thank you in advance.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire