我有很多控制器,我想在所有这些(实际上是所有项目)中设置这个代码,我该怎么做?
if( !empty(Input::get('lan')) ){
Auth::user()->language = Input::get('lan');
App::setLocale( Auth::user()->language );
}else{
App::setLocale( Auth::user()->language );
}
答案 0 :(得分:1)
您可以使用 Laravel的中间件。 中间件是一个包含请求处理的代码层,可以在处理请求之前或之后执行其他代码。
首先,您需要中间件类。它需要有一个名为 handle()的方法,它将执行所需的逻辑。在你的情况下,它可能看起来像这样:
package orginal;
public class ReadWriteExcelFile {
static XSSFWorkbook wb = null;
static XSSFRow row = null;
/**
* @param args
*/
public static void main(String[] args) {
try {
writeXLSFile();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void writeXLSFile() throws IOException {
String excelFileName = "C:\\Users\\RK\\Music\\500.xlsx";
String sheetName = "Sheet1";
wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName);
FileOutputStream fileOut = new FileOutputStream(excelFileName, true);
ArrayList arrList = new ArrayList();
for (int i = 0; i < 25; i++) {
arrList.add("Row ::" + i);
}
ArrayList aTemp1 = new ArrayList();
int r = 0;
// Writing first batch
// iterating r number of rows
for (r = 0; r < 20; r++) {
createData(sheet, r);
}
writeRec(fileOut);
for (int l = r; l < arrList.size(); l++) {
aTemp1.add(arrList.get(l));
}
// Writing second batch for remaining records extra than the bacth size.
for (int k = r; k < arrList.size(); k++) {
createData(sheet, k);
}
fileOut = new FileOutputStream(excelFileName, true);
writeRec(fileOut);
System.out.println("done");
}
private static void createData(XSSFSheet sheet, int r) throws IOException {
row = sheet.createRow(r);
// iterating c number of columns
for (int c = 0; c < 10; c++) {
XSSFCell cell = row.createCell(c);
cell.setCellValue("Cell " + r + " " + c);
}
}
private static void writeRec(FileOutputStream fileOut) throws IOException {
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
然后在 App \ Http \ Kernel 类中注册中间件,以便为每个请求执行它:
<?php namespace App\Http\Middleware;
use Auth;
use App;
class SetLang {
public function handle($request, Closure $next) {
if(empty($request->has('lan'))) {
if (Auth::user()) {
Auth::user()->language = $request->input('lan');
Auth::user()->save(); // this will do database UPDATE only when language was changed
}
App::setLocale($request->input('lan'));
} else if (Auth::user()) {
App::setLocale(Auth::user()->language);
}
return $next($request);
}
}
您可以在此处的文档中找到有关中间件的更多信息:http://laravel.com/docs/master/middleware
答案 1 :(得分:0)
似乎要使该中间件能够使用最新版本的Laravel(在5.8上运行),您需要将其放在$middlewareGroups
下,否则对Auth::user()
的调用始终为空。
在回答 jedrzej-kurylo 之后,只需将中间件移至:
protected $middlewareGroups = [
'web' => [
...
'App\Http\Middleware\SetLang',
],
];