首页 > 其他分享 >laravel常用辅助函数

laravel常用辅助函数

时间:2023-05-12 19:35:02浏览次数:34  
标签:laravel 辅助 函数 price products Str 100 string name

数组

use Illuminate\Support\Arr;

Arr::collapse([[1, 2, 3], [4, 5, 6], [7, 8, 9]]); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Arr::flatten(['name' => 'Joe', 'languages' => ['PHP', 'Ruby']]);  // 将多维数组中数组的值取出平铺为一维数组 ['Joe', 'PHP', 'Ruby']
[$keys, $values] = Arr::divide(['name' => 'Desk']); //$keys: ['name']  $values: ['Desk']

Arr::except(['name' => 'Desk', 'price' => 100], ['price']);  //['name' => 'Desk']
Arr::only(['name' => 'Desk', 'price' => 100, 'orders' => 10], ['name', 'price']); // ['name' => 'Desk', 'price' => 100]
Arr::first([100, 200, 300], function ($value, $key) {  // 200  Arr::first($array, $callback, $default);
    return $value >= 150;
});
Arr::last([100, 200, 300, 110], function ($value, $key) { // 300  Arr::last($array, $callback, $default);
    return $value >= 150;
});
Arr::where([100, '200', 300, '400', 500], function ($value, $key) {  // [1 => '200', 3 => '400']
    return is_string($value);
});
Arr::whereNotNull([0, null]); // [0 => 0]
Arr::pluck([  // ['Taylor', 'Abigail']
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
], 'developer.name');
Arr::pluck([  // [1 => 'Taylor', 2 => 'Abigail']
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
], 'developer.name', 'developer.id');
Arr::forget(['products' => ['desk' => ['price' => 100]]], 'products.desk');  //  ['products' => []]

Arr::get(['products' => ['desk' => ['price' => 100]]], 'products.desk.price'); // 100
Arr::get(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 0); // 0
Arr::has(['product' => ['name' => 'Desk', 'price' => 100]], 'product.name'); // true
Arr::has(['product' => ['name' => 'Desk', 'price' => 100]], ['product.price', 'product.discount']); // false
Arr::hasAny(['product' => ['name' => 'Desk', 'price' => 100]], ['product.price', 'product.discount']); // true

Arr::query([  // name=Taylor&order[column]=created_at&order[direction]=desc
    'name' => 'Taylor',
    'order' => [
        'column' => 'created_at',
        'direction' => 'desc'
    ]
]);
Arr::random([1, 2, 3, 4, 5]); //随机取一个
Arr::random([1, 2, 3, 4, 5], 2); //随机取2个  [2, 5]
Arr::dot(['products' => ['desk' => ['price' => 100]]]); //['products.desk.price' => 100]
Arr::undot([ // ['user' => ['name' => 'Kevin Malone', 'occupation' => 'Accountant']]
    'user.name' => 'Kevin Malone',
    'user.occupation' => 'Accountant',
]);

data_fill(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 100]]]
data_fill(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 10); // ['products' => ['desk' => ['price' => 100, 'discount' => 10]]]
data_fill([
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2'],
    ],
], 'products.*.price', 200);
data_get(['products' => ['desk' => ['price' => 100]]], 'products.desk.price');  // 100
data_get(['products' => ['desk' => ['price' => 100]]], 'products.desk.discount', 0); // 0
data_get([ // ['Desk 1', 'Desk 2'];
    'product-one' => ['name' => 'Desk 1', 'price' => 100],
    'product-two' => ['name' => 'Desk 2', 'price' => 150],
], '*.name');
data_set(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200); // ['products' => ['desk' => ['price' => 200]]]
data_set([
    'products' => [
        ['name' => 'Desk 1', 'price' => 100],
        ['name' => 'Desk 2', 'price' => 150],
    ],
], 'products.*.price', 200);
data_set(['products' => ['desk' => ['price' => 100]]], 'products.desk.price', 200, $overwrite = false); // ['products' => ['desk' => ['price' => 100]]]

 

 

字符串

use Illuminate\Support\Str;

e('<html>foo</html>');  // &lt;html&gt;foo&lt;/html&gt;
preg_replace_array('/:[a-z_]+/', ['8:30', '9:00'], 'between :start and :end'); //between 8:30 and 9:00

Str::after('This is my name', 'This is'); // ' my name'
Str::afterLast('App\Http\Controllers\Controller', '\\'); // 'Controller'
Str::before('This is my name', 'my name');  // 'This is '
Str::beforeLast('This is my name', 'is'); // 'This '
Str::between('This is my name', 'This', 'name'); // ' is my '

Str::contains('This is my name', 'my'); // true
Str::contains('This is my name', ['my', 'foo']); // true
Str::containsAll('This is my name', ['my', 'name']); // true
Str::startsWith('This is my name', 'This'); // true
Str::startsWith('This is my name', ['This', 'That', 'There']); // true
Str::endsWith('This is my name', 'name'); // true
Str::endsWith('This is my name', ['name', 'foo']); // true
Str::endsWith('This is my name', ['this', 'foo']); // false
//用来判断字符串是否与指定模式匹配
Str::is('foo*', 'foobar'); // true
Str::is('baz*', 'foobar'); // false

Str::studly('foo_bar'); // FooBar
Str::camel('foo_bar'); // fooBar
Str::snake('fooBar'); // foo_bar
Str::snake('fooBar', '-'); // foo-bar
Str::kebab('fooBar'); // foo-bar
Str::excerpt('This is my name', 'my', [
    'radius' => 3
]); // '...is my na...'  截断字符串
Str::excerpt('This is my name', 'name', [
    'radius' => 3,
    'omission' => '(...) '
]); // '(...) my name'
Str::limit('The quick brown fox jumps over the lazy dog', 20); // The quick brown fox...
Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)'); // The quick brown fox (...)
//将指定的字符串修改为以指定的值结尾的形式
Str::finish('this/string', '/'); // this/string/  
Str::finish('this/string/', '/'); // this/string/
//将给定的值添加到字符串的开始位置
Str::start('this/string', '/'); // /this/string
Str::start('/this/string', '/'); // /this/string
//将由大小写、连字符或下划线分隔的字符串转换为空格分隔的字符串,同时保证每个单词的首字母大写
Str::headline('steve_jobs'); // Steve Jobs
Str::headline('EmailNotificationSent'); // Email Notification Sent


Str::ascii('û'); // 'u'  尝试将字符串转换为 ASCII 值
Str::isAscii('Taylor'); // true
Str::isAscii('ü'); // false
Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'); // true
Str::markdown('# Laravel'); // <h1>Laravel</h1>
Str::markdown('# Taylor <b>Otwell</b>', [
    'html_input' => 'strip',
]); // <h1>Taylor Otwell</h1>
//重复的字符掩盖字符串的一部分
Str::mask('[email protected]', '*', 3); // tay***************
Str::mask('[email protected]', '*', -15, 3); // tay***@example.com

Str::padBoth('James', 10, '_'); // '__James___'
Str::padBoth('James', 10); // '  James   '
Str::padLeft('James', 10, '-='); // '-=-=-James'
Str::padLeft('James', 10); // '     James'
Str::padRight('James', 10, '-'); // 'James-----'
Str::padRight('James', 10); // 'James     '
Str::plural('car'); // cars
Str::plural('child'); // children
Str::singular('cars'); // car
Str::remove('e', 'Peter Piper picked a peck of pickled peppers.'); // Ptr Pipr pickd a pck of pickld ppprs.
Str::replace('8.x', '9.x', 'Laravel 8.x'); // Laravel 9.x
Str::replaceArray('?', ['8:30', '9:00'], 'The event will take place between ? and ?'); // The event will take place between 8:30 and 9:00
Str::replaceFirst('the', 'a', 'the quick brown fox jumps over the lazy dog'); // a quick brown fox jumps over the lazy dog
Str::replaceLast('the', 'a', 'the quick brown fox jumps over the lazy dog'); // the quick brown fox jumps over a lazy dog
Str::reverse('Hello World'); // dlroW olleH
Str::slug('Laravel 5 Framework', '-'); // laravel-5-framework 将给定的字符串生成一个 URL 友好的「slug」
Str::title('a nice title uses the correct case'); // A Nice Title Uses The Correct Case

Str::substrCount('If you like ice cream, you will like snow cones.', 'like'); // 2
Str::wordCount('Hello, world!'); // 2
Str::words('Perfectly balanced, as all things should be.', 3, ' >>>'); // Perfectly balanced, as >>>
Str::uuid();

Str::of('Taylor')
    ->when(true, function ($string) {
        return $string->append(' Otwell');
    }); // 'Taylor Otwell'
Str::of('tony stark')
    ->whenContains('tony', function ($string) {
        return $string->title();
    }); // 'Tony Stark'
Str::of('tony stark')
    ->whenContains(['tony', 'hulk'], function ($string) {
        return $string->title();
    }); // Tony Stark
Str::of('tony stark')
    ->whenContainsAll(['tony', 'stark'], function ($string) {
        return $string->title();
    }); // Tony Stark
Str::of('  ')->whenEmpty(function ($string) {
    return $string->trim()->prepend('Laravel');
}); // 'Laravel'
Str::of('Framework')->whenNotEmpty(function ($string) {
    return $string->prepend('Laravel ');
}); // 'Laravel Framework'
Str::of('disney world')->whenStartsWith('disney', function ($string) {
    return $string->title();
}); // 'Disney World'
Str::of('disney world')->whenEndsWith('world', function ($string) {
    return $string->title();
}); // 'Disney World'
Str::of('laravel')->whenExactly('laravel', function ($string) {
    return $string->title();
}); // 'Laravel'
Str::of('foo/bar')->whenIs('foo/*', function ($string) {
    return $string->append('/baz');
}); // 'foo/bar/baz'
Str::of('foo/bar')->whenIsAscii('laravel', function ($string) {
    return $string->title();
});// 'Laravel'

 

其它

//路径
public_path();
public_path('css/app.css');
resource_path();
resource_path('sass/app.scss');
storage_path();
storage_path('app/file.txt');

//url
action([UserController::class, 'profile'], ['id' => 1]);
asset('img/photo.jpg');
route('route.name');
route('route.name', ['id' => 1]);
url('user/profile', [1]);

auth()->user();
bcrypt('my-secret-password');
encrypt('my-secret-value');
decrypt($value);

blank('');
blank('   ');
blank(null);
blank(collect());
// true
blank(0);
blank(true);
blank(false);
// false
filled(0);
filled(true);
filled(false);
// true
filled('');
filled('   ');
filled(null);
filled(collect());
// false

cache('key');
cache('key', 'default');
cache(['key' => 'value'], 300);
cache(['key' => 'value'], now()->addSeconds(10));

collect(['taylor', 'abigail']);

config('app.timezone');
config('app.timezone', $default);
env('APP_ENV');
env('APP_ENV', 'production');

dispatch(new App\Jobs\SendEmails); //将给定的 任务 推送到 Laravel 任务队列
event(new UserRegistered($user)); //向监听器派发给定 事件

$request = request();
$value = request('key', $default);
return response('Hello World', 200, $headers);
return response()->json(['foo' => 'bar'], 200, $headers);

$value = session('key');
$value = session()->get('key');
session()->put('key', $value);
session(['chairs' => 7, 'instruments' => 3]);

$today = today(); //根据当前日期创建新的 Illuminate\Support\Carbon 实例
$now = now(); //为当前时间创建一个新的 Illuminate\Support\Carbon 实例

 

标签:laravel,辅助,函数,price,products,Str,100,string,name
From: https://www.cnblogs.com/caroline2016/p/17396116.html

相关文章

  • 终于找到了C++成员函数做函数指针的完美解决办法
    当然,这是转自别人的:https://www.codenong.com/19808054/之前因为这个没少废精力啊,这里记一下,感谢外国友人的回答.1#include<iostream>2#include<functional>3#include<string>4#include<sstream>5#include<memory>67usingnamespacestd;89......
  • 信捷套袋机自动装袋机程序自动入袋,自动双边热封 采用函数计算轴参数
    信捷套袋机自动装袋机程序自动入袋,自动双边热封采用函数计算轴参数已上机应用信捷触摸屏加XD5-60T6脉冲控制5台伺服通讯控制一台变频器,含触摸和程序屏源文件,程序带注解。含回原点点动绝对定位相对定位入门教程,弄懂了你就可以控制伺服步进ID:7512655957931620......
  • 催款锁机程序信捷12轴设备程序一共十级密码到时间锁机 含一屏多机和到时间锁机程序 ,C
    催款锁机程序信捷12轴设备程序一共十级密码到时间锁机含一屏多机和到时间锁机程序,C函数设置轴参数是学习的好资料双工位切换上料和机械手下料程序一万多步采用信捷触摸屏和XDPLCID:6225657428024007......
  • 【C++之内联函数和模板】
    内联函数(inline):1.使用关键字inline修饰的函数叫做内联函数,内联函数可以提升程序运行效率。2.内联函数是一种用空间换取时间的方法,省去了调用函数的时间,会将函数代码拷贝过来占用空间,所以很长的代码不适合转变内联函数。3.如果定义为inline的函数体过大,编译器优化时会忽略掉内......
  • 农村高中生源转型期提升学生二次函数建模能力的课堂探究
         农村高中是处于国内各乡镇地区的普通全日制高级中学,属于农村教育的“终极”阶段。从农村高中所处的区位条件来讲,当下国内城镇化进程不断加快,农村高中生源呈现为逐年递减的全新变化形势,同时面临着新课标下数学核心素养培养的新要求与任务。然而,以往农村高中数学教学......
  • Scala入门到放弃—02—函数
    函数方法定义def方法名(参数:参数类型):返回值类型={ //方法体 //最后一行作为返回值(不需要使用return)}defmax(x:Int,y:Int):Int={ if(x>y) x else y}packageorg.exampleobjectApp{defmain(args:Array[String]):Unit={println(a......
  • 19、函数的类型
    1.函数也是有类型的func(参数列表类型的数据类型)(返回值列表的数据类型)/***@authorly(个人博客:https://www.cnblogs.com/qbbit)*@date2023/5/1122:49*@tags喜欢就去努力的争取*/packagemainimport"fmt"funcmain(){ a:=10 fmt.Printf("%T\n",......
  • 使用golang编写支持C++调用的动态库,接口支持结构体和回调函数
    网上有很多例子介绍如何使用cgo实现C/C++与golang进行接口交互。我有个项目是使用Qt写的客户端程序,但Qt在需要使用redis、支持表单的web服务、mq或网络化日志库等需求时,往往需要加载一大堆第三方库,且编译复杂,跨平台(如Windows/linuxarm/linuxx86)编译时较为复杂。鉴于有使用go......
  • 17、函数
    1.是什么?函数就是执行特定任务的代码块2.函数的意义避免重复的代码增强程序的扩展性3.函数的使用步骤step1:函数的定义,也叫声明step2:函数的调用,就是执行函数中的代码4.函数的语法funcfuncName(paramName1type1,paramName2type2,......)(output1type1,outpu......
  • LR损失函数的两种形式
    1.label为1和0 2.label为1和-1因为:所以: 最后可以得到损失函数为: 参考资料https://zhuanlan.zhihu.com/p/362317339 ......