带有可选参数的 Laravel 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/54764278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:17:08  来源:igfitidea点击:

Laravel function with optional parameter

phplaravel

提问by Nana Qhuacy

In my web file, I have a route that accepts a $id as a value to be passed to a function within my PagesController. However, I want the function to still execute and show the intended form even when the $id is not passed to the function.

在我的 web 文件中,我有一个路由接受 $id 作为要传递给我的 PagesController 中的函数的值。但是,即使 $id 没有传递给函数,我也希望函数仍然执行并显示预期的形式。

web.php file

web.php 文件

Route::get('/request/{id}', 'PagesController@makeRequest');

PagesController.php file

PagesController.php 文件

public function makeRequest($id)
{
   if(!empty($id)){
      $target = Partner::find($id);
   }
   return view('pages.makeRequest')->with('target', $target);
}

makeRequest.blade.php

makeRequest.blade.php

<input type="text" class="form-control" value="{{$target->inst_name}}" required disabled>  

I want the page to display details from the database with the $id when provided or have empty spaces when the $id isn't provided.

我希望页面在提供 $id 时显示来自数据库的详细信息,或者在未提供 $id 时显示空格。

回答by Jignesh Joisar

As the Laravel Documentation states: Use Optional Parameterslike this:

正如 Laravel 文档所述:使用可选参数如下:

Route::get('/request/{id?}', 'PagesController@makeRequest'); //Optional parameter

Controller

控制器

public function makeRequest($id = null)
    {
        if(!empty($id)){
            $target = User::find($id);
            return view('pages.makeRequest')->with('target', $target); 
        } else {
            return view('pageslist'); ///set default list..
        }        
    }

回答by Nana Qhuacy

All your solutions were helpful. The main thing was that when I called just the view without passing $target to the view, the page displayed an error. So this is what I did.

你所有的解决方案都有帮助。主要的是,当我只调用视图而不将 $target 传递给视图时,页面显示错误。所以这就是我所做的。

Route::get('/request/{id?}', 'PagesController@makeRequest');

Then in the controller,

然后在控制器中,

public function makeRequest(Request $request, $id=null)
    {
        if ($id != null) {
            $target = Partner::find($id);
            return view('pages.makeRequest')->with('target', $target);
        }
        return view('pages.makeNullRequest');
    }

If you didn't understand what happened, I created a new view which had this instead of what I had posted in the question.

如果您不明白发生了什么,我创建了一个新视图,其中包含这个而不是我在问题中发布的内容。

<input type="text" class="form-control" value="" required readonly> 

Sorry I didn't update you guys in time. I think Jignesh Joisar came closest to helping me solve this issue. really appreciate all you guys. You're just awesome

抱歉没有及时给大家更新。我认为 Jignesh Joisar 最能帮助我解决这个问题。真的很感谢你们所有人。你真棒

回答by Furqan S. Mahmoud

This is the way I did it:

这是我这样做的方式:

  Route::get('index', 'SeasonController@index');

// controller

// 控制器

 public function index(Request $request )
    {
        $id= $request->query('id');
    }

The way you call it:

你这样称呼它:

localhost/api/index?id=7

回答by Mike

For me the answer was in the order that I listed the Routes in the routes file.

对我来说,答案是按照我在路由文件中列出路由的顺序。

The routes file will call the first one that matches the pattern.

路由文件将调用与模式匹配的第一个。

Route::get('/ohmy/{id?}', 'OhMyController@show');
Route::get('/ohmy/all', 'OhMyController@all');   //never gets called

Instead, put optional parameters at end of list:

相反,将可选参数放在列表末尾:

Route::get('/ohmy/all', 'OhMyController@all'); 
Route::get('/ohmy/{id?}', 'OhMyController@show');

回答by Kinjal Vithalani

For optional parameter pass id with ? in route and give $id = null in your function's parameter like this:

对于可选参数传递 id 与 ? 在路由中并在您的函数参数中给 $id = null ,如下所示:

Route::get('/request/{id?}', 'PagesController@makeRequest'); //Optional parameter

makeRequest($id = null) {

// Code here...
...

}


回答by Arvind Kala

in your routes file (web.php , as mentioned in your question)

在您的路由文件( web.php ,如您的问题中所述)

Route::get('/request/{id?}', 'PagesController@makeRequest');

and in your controller PagesController.php

并在您的控制器 PagesController.php 中

public function makeRequest($id = null)
{

}

To read more about this, just read https://laravel.com/docs/5.7/routing#parameters-optional-parameters

要了解更多相关信息,请阅读https://laravel.com/docs/5.7/routing#parameters-optional-parameters

回答by Mihir Bhende

You can use optionalparameter :

您可以使用可选参数:

Route::get('/request/{id?}', 'PagesController@makeRequest');

Now, as the parameter is optional, while defining the controller function you need to assign its default value to nullin argument declaration.

现在,由于参数是可选的,在定义控制器函数时,您需要null在参数声明中为其分配默认值。

<?php 

public function makeRequest($id = null)
{
   if($id){

        $target = Partner::findOrFail($id);

        return view('pages.makeRequest')->with(compact('target'));
   }

   // Return different view when id is not present
   // Maybe all targets if you want

   $targets = Partner::select('column1', 'column2')->get();

   return view('pages.all')->with('targets');

}

I am using findOrFailinstead of find. Its Laravel's very handy function which automatically throws a ModelNotFoundexception and for frontend user throws a simple 404 page.

我正在使用findOrFail而不是find. 它的 Laravel 非常方便的功能会自动抛出ModelNotFound异常,并为前端用户抛出一个简单的 404 页面。

So if anyone is accessing www.url.com/request/2, its a valid id then it will show a valid page with data. If the accessed url is www.url.com/request/blahblahthen it will throw 404. It avoids efforts of handling this manually.

因此,如果有人正在访问www.url.com/request/2,它是一个有效的 ID,那么它将显示一个包含数据的有效页面。如果访问的 url 是,www.url.com/request/blahblah那么它将抛出 404。它避免了手动处理这个问题。