Laravel and Eloquent help

Soldato
Joined
18 Oct 2002
Posts
7,614
Location
Sutton Coldfield, Birmingham
First venture with laravel and i'm trying to use Eloquent to help management my database.

I'm finding it difficult when trying to link tables together.

The two tables I want to join are as follows:-

- Properties
-- id
-- address
-- style_id

- Styles
-- id
-- name

I have two models, Properties and Property_Styles which are as follows

Code:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

class Properties extends Model
{
	
   use SoftDeletes;
   protected $dateFormat = 'Y-m-d H:i:s';
   protected $dates = ['deleted_at'];
	
    public function style()
    {
        return $this->hasOne('App\Models\propertyStyles');
    }

}

Code:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Property_Styles extends Model
{

   protected $table = 'property_styles';
   protected $dateFormat = 'Y-m-d H:i:s';
	
    public function properties()
    {
        return $this->belongsTo('App\Models\Properties');
    }

}

Then the controller

Code:
	public function index()
	{
		
		$properties = Properties::orderBy('property_address_1')->paginate(20);

		return View::make('plainTable')
			->nest('content', 'properties.propertiesTable', ['properties' => $properties])
			->with('page_title', 'Properties');

	}

Now this receives the properties fine I can't for the life of me figure out how to replace the style_id number with the actual style name in the view?

I thought about looping the properties array and trying to set it that way but is there an easier way?
 
Associate
Joined
26 Sep 2007
Posts
1,252
Location
Amsterdam
The main issue is in your model names. Whilst your tables should have pluralized names your models should be singular.

https://laravel.com/docs/5.1/eloquent#introduction

Eloquent assumes this convention meaning you don't need to specifically define which fields have relationships. If you do need to you can set the following
Code:
return $this->hasOne('App\PropertyStyle', 'id', 'property_style_id');
https://laravel.com/docs/5.1/eloquent-relationships

Once you have your relationships defined properly you can set a $with array on your Property model:
Code:
protected $with = ['style''];
This corresponds to whatever you've named your property_styles relationship to. This will mean every time you fetch a Property the style relationship will be resolved and populated on the object. Ensure you only do this one direction so you don't end up in a circular loop.
 
Last edited:
Back
Top Bottom