Laravel 4: Eloquent soft deletes and relationships

eloquent, laravel-4

Solution

This was solved by using the withTrashed() method when defining the relation in the model.

Original code:

public function client() {
    return $this->belongsTo('Client');
}

Solution:

public function client() {
    return $this->belongsTo('Client')->withTrashed();
}

Many thanks to Glad to Help.

Problem

I have 2 tables, clients and projects and a project is associated with a client. Both the clients and projects implement soft deletes to maintain the relationships for archival reasons i.e. even if I delete a client the project will still have the client information attached. My problem is that when I delete the client, the reference becomes inaccessible from the project and throws an exception. What I would like to do is soft delete the client but retain the client data from the project relationship. My blade code is as follows: ``` @if ($projects->count()) <table class="table table-striped table-bordered"> <thead> <tr> <th>Name</th> <th>Client</th> </tr> </thead> <tbody> @foreach ($projects as $project) <tr> <td>{{{ $project->name }}}</td> <td>{{{ $project->client->name }}}</td> <td>{{ link_to_route('projects.edit', 'Edit', array($project->id), array('class' => 'btn btn-info')) }}</td> <td> {{ Form::open(array('method' => 'DELETE', 'route' => array('projects.destroy', $project->id))) }} {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }} {{ Form::close() }} </td> </tr> @endforeach </tbody> </table> @else There are no projects @endif ``` Here are the migrations: ``` Schema::create('clients', function(Blueprint $table) { // Table engine $table->engine = 'InnoDB'; // Increments $table->increments('id'); // Relationships // Fields $table->string('name'); // Timestamps $table->timestamps(); // Soft deletes $table->softDeletes(); }); Schema::create('projects', function(Blueprint $table) { // Table engine $table->engine = 'InnoDB'; // Increments $table->increments('id'); // Relationships $table->integer ('client_id'); // Fields $table->string('name'); // Timestamps $table->timestamps(); // Soft deletes $table->softDeletes(); // Indexes $table->index('client_id'); }); ``` Many thanks.

Original source