Search code examples
phplaravellaravel-5eloquenteloquent-relationship

Laravel Eloquent Relationship with different foreign key


Laravel version is 7.0:

I have setup model relationships like this.

<?php

namespace App;


class Template extends Model
{

    protected $fillable = ['header_id', 'content', 'name'];

    public function header()
    {
        return $this->belongsTo('App\Header', 'header_id');
    }
}

In controller I can get template object with header.

<?php

namespace App\Http\Controllers;
use App\Template;

class TemplateController extends Controller
{

   public function show($id)
   {
     $template = Template::find($id);
   }
}

Now I can use $template->header in view.

How can I pass different header_id and get header relationship object? I would like to do as following:

<?php

namespace App\Http\Controllers;
use App\Template;

class TemplateController extends Controller
{

   public function show($id, $temp_header_id)
   {
     $template = Template::find($id);
     $template->header_id = $temp_header_id;
   }
}

I want to get new header relationship in view:

Is there any way to return new header relationship when I do $template->header in view.

Thank you


Solution

  • Yes you can do what you are looking to do, but kinda defeats the relationship in the database. You can assign any id to $template->header_id and then load the relationship using that new value:

    $template->header_id = 897;
    
    // load the relationship, will use the new value
    // just in case the relationship was already loaded we make sure
    // to load it again, since we have a different value for the key
    $template->load('header'); 
    
    $template->header; // should be header with id = 897