Reputation: 532
I have a table named 'contacts' and it has the 'is_company' field. This field gets value 0 and 1. And I have two controller named ContactController and CompanyController. I'm saving data to table from ContactController -> is_company = 0, from CompanyController -> is_company = 1.
I cannot use a single controller. Because views and other information which stored in the table are different.
Here is my route
Route::resource('contacts','ContactController')->middleware('auth');
Route::resource('companies','CompanyController')->middleware('auth');
And here is controller
public function show(Contact $contact)
{
$act = Activity::all();
$reg = Region::all();
$type = UserType::all();
$provinces = DB::table('regions')->where('parent', '=',0)->get();
$regions = DB::table('regions')->where('parent', '!=',0)->get();
return view('contacts.show', compact('contact','act','reg','type', 'provinces', 'regions'));
}
This function is the same at both controllers.
Here is a view of companies.index
<a class="btn btn-info" href="{{route('companies.show',$contact->id)}}"><i class="fas fa-pen"></i></a>
Here is a view of companies.show
<form role="form" action="{{route('companies.update', $contact->id) }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="card-body">
******
This method works normally when I doing something with the Contacts route. But I'm getting errors at CompanyController because there is no model with a named Company. How can I solve this? Any suggestions?
How can I use a single Model for two Controllers?
Upvotes: 0
Views: 1043
Reputation: 5149
Laravel ::resource()
routes automatically generate a set of routes based on a particular scheme. This scheme assumes that a model of the corresponding name exists.
https://laravel.com/docs/8.x/controllers#resource-controllers
For example, the following show
URL is presumed. You can see it is looking for a variable named company
, not contact
.
Route::get('companies/{company}','CompanyController@show');
You have a few options that come to mind:
contact
as the input.For example:
Route::get('companies/{contact}','CompanyController@show');
$contact
to $company
.public function show(Contact $company)
{
// ...
}
You could even extend the Contact model to pass through existing methods, if desired. Then you would reference the Company model in your controller instead of Contact. You could even set up a global scope to only return Companies when referencing this model, which may make this option very useful.
class Company extends Contact
{
protected $table = 'contacts';
// ...
}
Upvotes: 1