Relationship establishment

Posted 3 years ago by francoboy7

Hey everyone, I'm new to Laravel so i'm hitting walls after walls, but hopefully I'll get through. So I want to set a relation within my model.

Basically a user submit available dates to work and dates he doesn't want to work So A User hasMany Dates Available (Model : DatesAvailable) A User hasMany DatestoSwap and now i'm getting confused. Date Available belongsTo a User (or hasMany / belongsToMany) Dates to Swap belongsTo a User (or hasMany / belongsToMany)

User.php

<?php
namespace Horaire;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['first_name','last_name', 'email', 'password', 'matricule'];

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

    public function getswapdates()
    {

        return $this->hasMany('\Horaire\SwapDates');

    }

    public function getavailabledates()
    {

        return $this->hasMany('\Horaire\DatesAvailable');

    }

}

DatesAvailable.php

<?php

namespace Horaire;

use Illuminate\Database\Eloquent\Model;

class DatesAvailable extends Model
{
    protected $fillable = array('user_id', 'date', 'preferences_sector', 'preferences_jsn');

    public function user()
    {

        return $this->belongsTo('User');

    }
}

SwapDates.php

<?php

namespace Horaire;

use Illuminate\Database\Eloquent\Model;

/**
 * Class SwapDates
 * @package Horaire
 */
class SwapDates extends Model
{
    //
    protected $fillable = array('user_id', 'start', 'end', 'shift_number', 'sector');

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function user()
    {

        return $this->belongsTo('User');

    }







}

Now I want to test this so in route.php

Route::get('{id}', function($id)

{
    $user = User::find($id)->first();

    $swap = SwapDates::where('user_id', $user->id);

    echo  $swap;

});

And it returns :

1/1
ErrorException in routes.php line 69:
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

Any ideas ?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.