【问题标题】:Laravel: How to pass data from form to controller without using Request objectLaravel:如何在不使用 Request 对象的情况下将数据从表单传递到控制器
【发布时间】:2022-11-18 22:01:30
【问题描述】:

使用 Laravel,我有自动进程和使用 Web 界面的用户都使用的逻辑。 它从数据库表中获取过滤后的数据。 只有 1 个过滤条件。我想为这两个目的使用相同的方法。

看法

            <form action="getJobs" target="_blank" class="mx-4">
                @csrf
                <input type="submit" value="Get Jobs">
                <select class="form-control" id="category" name="category">
                    <option value="">Select a Category</option>
                    @foreach ($categories as $category)
                        <option value="{{ $category}}">{{ $category}}</option>
                    @endforeach
                </select>
            </form>

控制器

    public function getJobsForCategory($category) {
        //Get all jobs from the database where category=$category
    }

    public function getJobsForCategoryFromBrowser(Request $request) {
        //Get all jobs from the database where category=$request->category
    }

请注意,类别不是模型。它只是一个字符串变量。

有没有一种方法可以在不使用 Request 对象的情况下将数据从表单传递到控制器?

或者(恐怖),在没有用户交互的应用程序其他地方使用此逻辑时,我是否应该伪造一个请求?

我找到的每个答案似乎都会导致在 Controller 中使用 Request 对象。

【问题讨论】:

  • 试试这个:在web.php - Route::get('/something/{test}', function ($test) { dd($test); }); 和你的浏览器中:127.0.0.1:8000/something/hello

标签: laravel


【解决方案1】:

您应该将逻辑抽象为服务类之类的东西,然后从您的 HTTP 控制器以及您想要使用它的任何其他地方调用该服务类(例如命令)。服务类不应接收 Request 对象。

<?php

namespace AppServices;

class JobService
{
    public function getJobsForCategory(string $category)
    {
        // Do some business logic
    }
}
<?php

namespace AppHttpControllers;

use AppServicesJobService;
use IlluminateHttpRequest;

class JobController extends BaseController
{
    public function getJobsForCategory(Request $request, JobService $service)
    {
        $jobs = $service->getJobsForCategory($request->category);
        
        // Do some HTTP response
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多