从Laravel 5.6升级到6.0后,调用未定义的str_random()函数不起作用。

41

我已经将Laravel从5.6升级到6.0。 之前,控制器上的默认辅助函数正常运行,但现在它显示为“未定义”。 在我的控制器中,我使用了以下内容。

$filename = str_random(12);

我遇到了以下错误:

message: "调用未定义的函数 App\Http\Controllers\str_random()"

我也使用了 random() 函数,但它显示相同的错误信息。

请问有人可以指导我该怎么做吗?

我已经执行了如下命令:

composer dump-autoload

但我遇到了同样的错误。


1
据我所知,str_random()在5.8中已被删除,似乎根本不受支持。请改用以下方法: https://laravel.com/docs/6.x/helpers#method-str-random - Lukasz Formela
请问您能否在文档中指出“这些函数”仍然得到支持?https://laravel.com/docs/6.x/helpers#method-str-random 显示它是Str::random() - brombeer
@kerbholz:您好先生,非常抱歉,我看到的是5.6文档而不是6.0的。现在我已经下拉顶部选择框并将版本设置为6.0,现在我可以看到您所写的是正确的。 - Vishal Srivastava
这个回答解决了你的问题吗?在Laravel 6.0中出现“Call to undefined function str_slug()”错误。 - ManojKiran A
4个回答

117

影响可能性:高 Laravel 6 升级指南

Laravel 6中,所有的str_array_助手函数已经移动到新的laravel/helpersComposer包中,并从框架中删除。如果需要,您可以更新所有对这些助手函数的调用,改为使用Illuminate\Support\StrIlluminate\Support\Arr类。或者,您可以添加新的laravel/helpers包到您的应用程序中继续使用这些助手函数:

composer require laravel/helpers

如果不想添加包,则使用StrArr类。

例如:

Str::random(12)

https://laravel.com/docs/master/helpers#method-str-random


Str::replace不可用,我该使用什么替代它?如果我想要进行替换。 - Anonymous Girl
使用内置的 str_replace 函数,否则请遵循我的答案。 - Jignesh Joisar

41

添加以下字符串库。

use Illuminate\Support\Str;

现在您可以按如下方式使用它。

$filename = Str::random(40)

或者,安装以下软件包。

composer require laravel/helpers

0
在我的情况下,我没有在我的应用程序代码中使用任何字符串辅助函数,所以我只需要删除编译的类文件:
php artisan clear-compiled

-1

使用代码 ::

<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;



   public function index()
    {
        $count=15;
        try {
            DB::statement('truncate users');
            DB::beginTransaction();
            while ($count--){
                $id = DB::table('users')->insertGetId( [
                    'name'=>'Sample'.$count,
                    'password'=>random_int(1000000,99999999)
                ]);
                foreach (range(1,rand(1,3)) as $index ){
                    DB::insert('INSERT INTO posts (userid,title,body) VALUES (:userid,:title,:body)',[
                            'userid'=>$id,
                            'title'=>str::random(15),
                            'body'=>str::random(50),
                        ]);
                }
                DB::commit();
            }
        }catch (\Exception $errors){
            DB::rollBack();
            Log::error($errors);
            return "mission filed";
        }
    }

代码冗余过多,抱歉。 - Azamat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接