【问题标题】:Laravel get data from database with ID from unique URLLaravel 从具有唯一 URL 的 ID 的数据库中获取数据
【发布时间】:2020-10-26 12:53:39
【问题描述】:

我有一个简单的问题,但对我来说很难解决。

我的 excel 插件创建唯一的 URL,并将数据 (param1,mobile_number,message) 发送到 Laravel API。主要标识符是param1

Laravel route

Route::get('/{param1}', 'SendSmsController@index')->name('sendSms');

database

id  |  param1  |  mobile_number  |  message     |
----------------------------------------------------------
1   |  abc     |  123456789      |   Hi there   |

我的目标是当我打开 URL https://my.web.com/abc 时,我收到带有 message 的短信到我的手机,它存储在数据库中。

但问题是如何在controller 我的$mobile_number 中识别URL 中的param1

当我用dd($param1) 打开网址时,得到abc

有没有办法从数据库中获取其他列?

laravel controller

public function index($param1)
{
    return view('login')->with('param1'=>$param1);
}

【问题讨论】:

    标签: php database laravel routes


    【解决方案1】:

    首先,您需要在路由中的param1 之前添加任何前缀,因为任何路由都会匹配此参数,请参阅此Answer 了解更多详细信息,我们将考虑此路由

    Route::get('send/sms/{param1}', 'SendSmsController@index')->name('sendSms');
    

    第二次从路由参数中获取记录有两种方式

    1. 你可以这样做
    public function index($param1)
    {
       $sms = Sms::where('param1', $param1)->first();
       
       // now you can access mobile_number,message from $sms
    }
    
    1. 如果您的 param1 是唯一的,您可以添加到您的 Sms 模型中
    /**
    * Get the route key for the model.
    *
    * @return string
    */
    public function getRouteKeyName()
    {
        return 'param1';
    }
    

    现在你可以在你的控制器中做

    public function index(Sms $param1)
    {
       // now you can access mobile_number,message from $param1 instance
    }
    

    【讨论】:

    • ok 第二种方法有效,$sms = Sms::where('param1', $param1)->first(); dd($sms) 返回包含数据库中所有数据的数组。我如何将它们分配给变量? $mobile_number = ? 谢谢
    • 您可以使用extract($sms->toArray());,现在您将有 4 个变量代表每个键,$id$param1$mobile_number$message
    【解决方案2】:

    首先将路由方法更改为 Post,然后将您的 mobile_number 或 id 发送到路由

    // inside web.php
    Route::post('/{param1}', 'SendSmsController@index')->name('sendSms');
    

    在你的控制器中

    public function index(Request $request)
    {
         // if you send id
         $mobile_number = Model::find($request->id)->mobile_number;
         // if you send mobile_number
         $mobile_number = Model::where('mobile_number', $request->mobile_number)->first();
    
         // the logic to send SMS to $mobile_number
    }
    

    【讨论】:

    • /{param1} 不好,因为所有其他路由都会与此匹配。
    • @Zack 当我将route 更改为无法显示URL 时还有其他方法吗?
    • 当您说“无法显示 URL”时,我不明白。你能解释一下吗
    • @Zack 将 get 更改为 post 返回此错误:405 Method Not Allowed
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    相关资源
    最近更新 更多