1

Como puedo mostrar el nombre del cliente con el que se relaciona?

Migracion projects

Schema::create('projects', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre', 60);
            $table->string('descripcion');
            //para relacionar con cliente
            $table->integer('client_id')->unsigned();
            $table->foreign('client_id')
                ->references('id')->on('clients')
                ->onDelete('cascade');

Migracion clients

Schema::create('clients', function (Blueprint $table) {
            $table->increments('id');
            $table->string('nombre', 60);

Projects controller

use App\Project;
use App\Client;
public function index()
    {
        $projects = Project::all();
        return view('admin/projects.index',compact('projects'));
    }

Model project

class Project extends Model
{
public function clients(){
        //Este proyecto pertenece a un cliente
        return $this->belongsTo('App\Client');
    }
}

Model Client

class Client extends Model
{
public function projects(){
        //Este cliente tiene muchos proyectos
        return $this->hasMany('App\Project');
    }
}

Como puedo mostrar el nombre del cliente con el que se relaciona en la vista? Me sale Trying to get property of non-object

@foreach($projects as $project) 
    <tbody> 
        <tr> 
            <th scope="row">{{$project->id}}</th> 
            <td>{{$project->nombre}}</td> 
            //AQUI//AQUI//AQUI//AQUI
            <td>{{$project->clients->nombre}}</td> //AQUI
            <td>{{$project->descripcion}}</td> 
            <td class="form-inline">
                <a href="{{ route('admin.projects.edit', $project->id) }}" class="btn btn-primary">Editar</a>
                {!!Form::open(['route'=>['admin.projects.destroy', $project->id], 'method' => 'DELETE'])!!}
                {!!Form::submit('Eliminar',['class'=>'btn btn-danger'])!!}
                {!!Form::close()!!}  
            </td> 
        </tr> 

    </tbody> 
@endforeach

2 respuestas 2

2

Para mantener coherencia con la forma como funciona Laravel y el método belongsTo, sugiero que utilices el singular cuando declaras la relación en Project y/o que agregues la llave foránea como segundo parámetro:

class Project extends Model
{
    public function client(){
        //Este proyecto pertenece a un cliente
        return $this->belongsTo('App\Client');
    }
}

Aquí tienes la referencia de Laravel (5.2) :

/**
 * Define an inverse one-to-one or many relationship.
 *
 * @param  string  $related
 * @param  string  $foreignKey
 * @param  string  $otherKey
 * @param  string  $relation
 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
 */
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
{
    // If no relation name was given, we will use this debug backtrace to extract
    // the calling method's name and use that as the relationship name as most
    // of the time this will be what we desire to use for the relationships.
    if (is_null($relation)) {
        list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);

        $relation = $caller['function'];
    }

    // If no foreign key was supplied, we can use a backtrace to guess the proper
    // foreign key name by using the name of the relationship function, which
    // when combined with an "_id" should conventionally match the columns.
    if (is_null($foreignKey)) {
        $foreignKey = Str::snake($relation).'_id';
    }

    $instance = new $related;

    // Once we have the foreign key names, we'll just create a new Eloquent query
    // for the related models and returns the relationship instance which will
    // actually be responsible for retrieving and hydrating every relations.
    $query = $instance->newQuery();

    $otherKey = $otherKey ?: $instance->getKeyName();

    return new BelongsTo($query, $this, $foreignKey, $otherKey, $relation);
}
2
  • Ya encontre el error laraveles.com/foro/viewtopic.php?id=5309 Estaba en client_id y debe ser clients_id Es decir debe ser llamado igual que la tabla mas _id //para relacionar con cliente $table->integer('clients_id')->unsigned(); $table->foreign('clients_id') ->references('id')->on('clients') ->onDelete('cascade'); ->references('id')->on('clients') ->onDelete('cascade');
    – ztvmark
    el 2 may. 2016 a las 1:44
  • Es lo mismo que está explicado en mi respuesta, con otras palabras.
    – Shaz
    el 2 may. 2016 a las 1:45
1

Ya encontre el error http://laraveles.com/foro/viewtopic.php?id=5309 Estaba en client_id y debe ser clients_id Es decir debe ser llamado igual que la tabla mas _id //para relacionar con cliente $table->integer('clients_id')->unsigned(); $table->foreign('clients_id') ->references('id')->on('clients') ->onDelete('cascade'); ->references('id')->on('clients') ->onDelete('cascade');

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.