简体   繁体   中英

unable to save foreign key into my table using laravel 5.5

i am trying to save foreign key which coming from another table into my controller method but i am unable to save this and stuch in this issue:

what i am trying to do here is there is business_id which is FK coming from business_master table:

My controller method:

           $businessId = Input::get('business_id');
        $page = new Page();
        $page->page_name = Input::get('page_name');
        $page->page_url  = Input::get('page_url');
        $page->business()->attach($businessId);
        $page->business_id = $businessId;

        $page->save();
        $resultArray = ['status' => 1, 'message' => 'Page url added!', 'dataArray' => $page];

    }

and my page model:

        class Page extends Model
   {
       protected $table = 'page_master';

      protected $fillable = ['business_id','page_url','page_name'];

      public function business()
{
    return $this->hasMany('App\Business','business_id','id');
}

error i am getting here is

BadMethodCallException: Call to undefined method Illuminate\Database\Query\Builder::attach()

i desperately want to store business_id (fk) but i am unable to do that your any help will be highly appreciated!

You have an error because only instance can be attached in many to many relationsip

$page->business()->attach($businessId);

Try bussiness create()

$page->business()->create([]);

Remove the line

$page->business()->attach($businessId);

Use only

$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url  = Input::get('page_url');
$page->business_id = $businessId;
$page->save();

The code will work for you.

It's good that you are using $fillable as it's help In the Eloquent ORM to avoid the mass assignment of such fields, we define the list of fields in the model under the fillable, so that when we send the array of values to model it will directly process the operation on depends upon the action like create, update, delete, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM