mardi 1 septembre 2015

Laravel 5 - oneToMany relationship always null

I'm new to Laravel, and using Laravel 5 i'm having trouble returning an array from my database.

I have several "acts", and each act has many "banners". Whenever I try to get output from my array of banners ( $act->banners->count() ), i find it throws an error because it is null.

Here is the code:

routes.php:

Route::model('banners', 'Banner');
Route::model('acts', 'Act');

// Controller routes
Route::resource('acts', 'sf_ActController');
Route::resource('acts.banners', 'sf_BannerController');


Route::bind('banners', function($value, $route) {
    return App\Banner::whereact_id($value)->first();
});
Route::bind('acts', function($value, $route) {
    return App\Act::whereact_id($value)->first();
});

Act.php (model)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Act extends Model
{
protected $table = 'sf_act';
protected $primaryKey = 'act_id';

public function act() {
      return $this->hasMany('Banner');

    }
}

Banner.php (model)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Banner extends Model
{

  protected $table = 'sf_banner';
  protected $primaryKey = 'banner_id';

  public function banner() {
        return $this->belongsTo('Act' , 'act_id' , 'act_id');
  }
}

sf_ActController.php (controller)

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Act;
use App\Banner;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use Input;
use Redirect;

class sf_ActController extends Controller
{
  public function show(Act $act)
  {

  //pass object to correct view
  return view('pages.acts.show' , compact('act'))->with('banner', Banner::find($act));
  }

acts/show.blade.php (view)

<!-- /resources/views/acts/show.blade.php -->
@extends('app')

@section('content')
<h2>{{ $act->act_title }}</h2>

  {{ $act->banners->count() }}

at this point I get the following error:

FatalErrorException in a03036ad81fb4e6d90e9fe5e3da62c65 line 7: Call to a member function count() on null

Why am I not fetching my banner data!? (The title variable in the h2 tags outputs fine, so the db and everything up until that point is working.)Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JK3ZnN
via IFTTT

Aucun commentaire:

Enregistrer un commentaire