search
HomeBackend DevelopmentPHP TutorialUncover Laravel's Hidden Treasures

揭开 Laravel 隐藏的宝藏

Many developers using Laravel may have only scratched the surface of what the framework has to offer. While the documentation does cover the most common use cases and obvious features, it doesn't cover everything.

Don't get me wrong, the documentation is great, it's just that there are so many things you can do that it's hard to document everything. So, we’re going to take a look at some of the hidden gems lurking in Laravel.

Cascading View

Available time: v4.0.0

Record:No

Views can be cascaded like configuration files. Cascading views are very useful when developing scalable theming systems. Consider the following directory structure.

/app
    /views
        /blog
            /index.blade.php
/themes
    /default
        /views
            /blog
                /index.blade.php
            /theme.blade.php

The idea is that when we return View::make('theme::blog.index'); it will first be in the themes/default/views directory Search, find the view if not found, fall back to app/views.

To do this, we use View::addNamespace to register our own namespace in both locations.

View::addNamespace('theme', [
    base_path().'/themes/default/views',
    app_path().'/views'
]);

gather

Available time: v4.0.0

Record:Part

Collections are a great way to interact with and manage arrays. Collections have a variety of convenience methods and implement many useful interfaces, such as ArrayableInterface, IteratorAggregate, and JsonableInterface.

Suppose we are building a small blog engine that uses flat files for storage. We want to be able to perform operations such as sorting, filtering, and paging.

Implementing a blog engine is beyond the scope of this article, but assume we have an array $articles, and each member of the array is an instance of the Article class. Then all we need to do is get a new instance of Collection and give it our array of articles.

$articles = new Illuminate\Support\Collection($arrayOfArticles);

Sort

Using collections we can sort articles. Let’s sort the articles and display the most recently updated ones first. For the purposes of this article, we assume that when loading an article from the file system, we set the updatedAt attribute to the last modification time of the file.

$articles->sortByDesc(function ($article) { 
    return $article->updatedAt; 
});
The

sortBy and sortByDesc methods accept a callback that should return a value that can be used to sort the collection. In our case, we can simply return the last modification time of the article, and the collection can be sorted based on that time.

filter

Similar to sorting, we can also use collections to filter our articles, just like the WHERE clause in MySQL. Let's filter our articles based on searches that may have been run.

<?php

$searchQuery = 'Laravel rocks!';

$results = $articles->filter(function ($article) use ($searchQuery) {
    return preg_match(sprintf('/%s/m', $searchQuery), $article->body);
});
The

filter method actually returns a new instance of Illuminate\Support\Collection, so we need to assign it to the $results variable. This new collection will only contain articles that mention "Laravel rock!"

Paging

Using this collection, we can paginate articles so that there are not too many articles on a single page.

$perPage = 1;

$page = Input::get('page', 1);

if ($page > ($articles->count() / $perPage)) {
    $page = 1;
}

$pageOffset = ($page * $perPage) - $perPage;

$results = $articles->slice($pageOffset, $perPage);

Using the slice method, we extract a portion of the articles in the collection and assign it to the $results variable.

This example can be further implemented by creating a new instance of Laravel's Paginator class. This way it can generate all the page numbers and links for you.

there are more!

We can get a random article:

$article = $articles->random();

We can also iterate over our collection of articles as if it were a regular array. This is all thanks to the IteratorAggregate and ArrayIterator interfaces.

foreach ($articles as $article) {
    echo $article->body;
}

We can even convert articles to regular arrays or their JSON representation.

$array = $articles->toArray();
$json = $articles->toJson();

One of the coolest methods is probably groupBy, which allows us to group articles by a specific key. Imagine that each article has some metadata at the top that is parsed and removed from the article body.

Although parsing this metadata is beyond the scope of this article, we assume it is parsed and is a property on the Article instance. You can then use groupBy to group the articles by the category they were published in.

$results = $articles->groupBy('category');

All articles sharing the same category will be grouped. Then you can get articles in a specific category.

foreach ($results->get('tutorial') as $article) { 
    echo $article->body; 
}

Collections are one of the best hidden gems Laravel has to offer.

Regular Expression Filter

Available time: v4.1.19

Record:No

Filtering routes in Laravel is a common task that many of us perform in all our projects. Filters allow you to perform tasks such as user authentication or rate limiting before or after a route is triggered. We create filters using Route::filter and can apply them to individual routes, route groups, or use Route::when and apply to matching patterns.

Route::filter('restricted', function($route, $request, $group)
{
    // Restrict user access based on the value of $group
});

Route::when('admin/*', 'restricted:admin');

在此示例中,我们创建一个 restricted 过滤器,它需要一个参数 $group$route$request 参数始终提供给 before 过滤器。

但是如果我们想要更大的灵活性怎么办?假设我们想要将过滤器应用于所有 admin 路由除了 admin/login。我们可以使用路线组并将相关路线移至组外。或者我们可以使用 Route::whenRegex 并编写我们自己的正则表达式。

Route::whenRegex('/^admin(\/(?!login)\S+)?$/', 'restricted:admin');

此正则表达式只是确保它仅适用于以 admin 开头且后面不跟 /login 的路由,但后面可以跟任何其他内容。出色的。现在,我们将 restricted:admin 过滤器应用于除 admin/login 路由之外的所有路由。

消息包

可用时间: v4.0.0

记录:部分

毫无疑问,您已经使用 Illuminate\Support\MessageBag 一段时间了,甚至没有意识到。 MessageBag 扮演的最大角色是在使用 Laravel 内置验证器时包含所有验证错误。

每个视图中都有一个 $errors 变量,该变量包含空的 MessageBag 实例或使用 Redirect::to('/')->withErrors($validator); 刷新到会话的实例

当在特定输入下方显示错误消息时,很多人可能会在表单中执行类似的操作。

{{ Form::text('username', null) }}
@if($errors->has('username'))
    <div class="error">{{ $errors->first('username') }}></div>;
@endif

您实际上可以完全删除 if 语句,并使用 first 方法的第二个参数将消息包装在 div 中。

    {{ Form::text('username', null) }}
    {{ $errors->first('username', '<div class="error">:message</div>') }}

好多了,好多了!

流利

可用时间: v3.0.0

记录:部分

Fluent 类已经存在很长时间了,当使用模式生成器创建迁移时,它实际上在框架本身内使用。 Laravel 3 和 Laravel 4 之间,类本身几乎没有变化,唯一大的区别是多了一些接口。

要使用 Fluent 类,您所需要做的就是获取一个实例,然后就可以了。

$user = new Illuminate\Support\Fluent;
$user->name('Jason')->country('Australia')->subscriber();

该实例现在定义了 3 个属性:name,值为 Jasoncountry,值为 Australiasubscriber,值为布尔值 true

在 Laravel 4.1 之前,您只能从实例中真正设置和获取属性。从 Laravel 4.1 开始,您可以使用 toArraytoJson 方法分别获取属性数组及其 JSON 表示形式。

从 Laravel 4.2 开始,该类还实现了 JsonSerialized 接口,这意味着您可以将实例直接传递到 json_encode 中。

还有更多!

我们已经研究了 Laravel 框架的几个有用的精华。但是,正如您所猜测的,框架内还有更多内容。

了解 Laravel 可能提供的其他功能的最佳方法是深入研究源代码。它并不像您想象的那么可怕,您将学到很多关于您正在构建的框架的知识。

如果您发现了其他宝石,请随时在评论中分享!

The above is the detailed content of Uncover Laravel's Hidden Treasures. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Customizing/Extending Frameworks: How to add custom functionality.Customizing/Extending Frameworks: How to add custom functionality.Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function