I am confused in this problem i have two model one is (business_master) and other one is ( page_master)
I want to save primary key (id) from business_master table to (page_master) as Fk (business_id).
Right now i hardcoded business_id in my controller.
My Controller:
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business_id = 1;
$page->save();
and its model:
class Page extends Model
{
protected $table = 'page_master';
protected $fillable = ['business_id','page_url','page_name'];
}
And my businees_master Model:
class Business extends Model
{
protected $table = 'business_master';
protected $fillable = ['user_id','business_name','business_url'];
}
how i can save business_id into my page_master table using relationships? Any help would be highly appreciated!
public function addPage(Request $id)
{
$fieldsValidation = [
'page_name' => 'required|unique:page_master,page_name',
'page_url' => 'required|unique:page_master,page_url',
];
$validator = Validator::make(Input::all(), $fieldsValidation);
if ($validator->fails()) {
$resultArray = [
'status' => 0,
'message' => $validator->errors()->first(),
'dataArray' => []
];
} else {
$business = Business::find(2);
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business()->associate($business);
$page->save();
$resultArray = ['status' => 1, 'message' => 'Page url added!', 'dataArray' => $page];
}
return Response::json($resultArray, 200);
}
So you have two models
1) Business
2)Page
You have to define one to many relationship , So define relation pages in Business model
public function pages()
{
return $this->hasMany('App\Page');
}
And You have to define the Inverse relationship also in the Page model,
public function business()
{
return $this->belongsTo('App\Business');
}
After defining relationships, you can query the relationships .
Like you are trying this query, So with the relationship you can do,
$business = \Business::find(1); //here 1 as you gave but you can pass id as per your requirement
$page = new Page();
$page->page_name = Input::get('page_name');
$page->page_url = Input::get('page_url');
$page->business()->associate($business);
$page->save();
This will help you for sure. But you have to read the blog and understand the Laravel relationship
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.