mardi 30 juin 2020

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire