我是 laravel 5.4.i 开发的search_code这样的控制器的新手。
public function search_code(Request $request){
$query = $request->search;
$queryType = $request->institute; // 'id' or 'name'
$items = DB::table('registerdetails');
if($queryType == 'id'){
$items = $items->where('trainee_id', 'LIKE',"%$query%");
}
if($queryType == 'full_name'){
$items = $items->where('full_name', 'LIKE',"%$query%");
}
$items = $items->get();
return view('traineeattendance.index')->with('items',$items);
}
我需要的是$item需要通过并从该控制器以两个不同的视图调用,例如
return view('traineeattendance.index')->with('items',$items);
和
return view('traineeattendance.attendance')->with('items',$items);
我该怎么做?
首先,停止在 MVC 框架中使用 DB 外观,除非它是非常复杂的查询。改为创建模型
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class RegisterDetails extends Model
{
protected $table = 'registerdetails';
/* Look into documentation for rest of the fields */
}
然后,对于搜索所需的所有内容,创建模型范围
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class RegisterDetails extends Model
{
protected $table = 'registerdetails';
public static function scopeTrainee($query, $input)
{
if(!empty($input)) {
$query->where("trainee_id", $input);
}
}
public static function scopeFullname($query, $input)
{
if(!empty($input)) {
$query->where("full_name", 'LIKE', $input);
}
}
}
简化控制器的代码
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsRegisterDetails;
class RegisterDetailsController extends Controller
{
public $data = [];
public function search_code(Request $request){
if($request->institute == 'id'){
$this->data['items'] = RegisterDetails::Trainee($request->search)->get();
}
if($request->institute == 'full_name'){
$this->data['items'] = RegisterDetails::FullName($request->search)->get();
}
return view('traineeattendance.index', $this->data);
}
}
现在索引视图有项目数据,如果您在索引视图中使用考勤视图,它也可以访问此数据。
如果索引和出勤率是不同的视图(一个不包括在另一个视图中(,那么您在设计级别做错了什么,您需要进一步解释这种情况
<?php
namespace AppProviders;
use IlluminateSupportFacadesView;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
View::share('items', search_code()); // this line will inject the return value of search_code() in all views in your app
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
使用类似view::share('variable_name', 'variable_value')
.
您的案例:
转到启动方法上的应用服务提供程序,添加以下行:*不要忘记导入类
然后在引导方法上添加行:
View::share('items', search_code());
这将从方法search_code()
中获取返回的值,并使其作为$items
提供给所有视图
像这样:转到应用程序 - 提供程序 - 应用程序服务提供商上的AppServiceProviders.php
,并在引导方法上添加以下内容,包括顶部的命名空间。
use IlluminateSupportFacadesView;
use AppHttpControllersYourController;
public function boot()
{
$controller = new YourController;
View::share('items', $controller->search_code());
}