In web.php I have this route which opens a form:
$this->namespace('Users')->prefix('users')->group(function (){
$this->get('/create' , 'UserController@create');
});
And this route returns an array of countries. I use that array to fill a select box via ajax in the form.
Route::namespace('API')->prefix('api')->group(function () {
$this->get('/get-country-list', 'LocationsController@index');
});
Controller:
app\\Http\\Controllers\\API\\LocationsController
class LocationsController extends Controller
{
public function index()
{
return DB::table('countries')->pluck("name","id")->all();
}
...
app\\Http\\Controllers\\Users\\UserController
class UserController extends Controller
{
public function create()
{
return view('panel.users.home.create.show');
}
...
How can I call LocationsController@index
in create()
function? what is the best method?
you can try return redirect(route('...'));
instead of return view()
in actions.
update
Because you just want to get Countries list instead of redirection. So do small tuning, separate the data manipulating function
from the action function
:
protected function getCountries() {
return DB::table('countries')->pluck("name","id")->all();
}
function index(Request $request) {
return $this->getCountries();
}
function create(Request $request) {
$countries = $this->getCountries();
return view('panel.users.home.create.show', compact('countries'));
}
I think you should try a different approach. What you seem to be trying to do is reuse this cumbersome query:
DB::table('countries')->pluck('name', 'id')->all();
That's good! However your index()
function is a controller endpoint and which returns a response and isn't really suitable for being reused in other controller endpoints. When I am in a similar situation I usually do one of two things,
class UserController extends Controller
{
public function index()
{
return $this->countryNames();
}
public function create()
{
// $countryNames = $this->countryNames():
return view('panel.users.home.create.show');
}
public function countryNames()
{
return DB::table('countries')->pluck('name', 'id')->all();
}
}
DB
facade. class UserController extends Controller
{
public function index()
{
return Country::names();
}
public function create()
{
// $countryNames = Country::names();
return view('panel.users.home.create.show');
}
}
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.