This article compiles and shares six Laravel Eloquent tips that can improve code readability. I hope it will be helpful to everyone!
Eloquent is the ORM used by Laravel by default. Active recording mode is used. Allows you to interact with the database in an easier way. Each individual model represents a table in the database that you can operate on. In this article, we will show you more or less hidden secrets, methods and properties that you may not know about to improve your code.
Snake naming attribute
The snake naming attribute is an interesting attribute. Let's see what the code says:
/** * 指示是否在数组上使用蛇形大小写属性。 * * @var bool */ public static $snakeAttributes = true;
People often use this property incorrectly to change the way the property is accessed. Many people believe that if you change this property, you can easily access the property using camelCase annotations. But in fact, it's not. We strongly recommend you not to use it. When the model is output as an array, just define whether the attribute should be camelCase or SnakeCase.
If you want to base naming on camelCase, we recommend you check out Kirk Bushell's package Eloquence by Kirk Bushell.
Pagination
If you are If you use Laravel's Eloquent ORM, then this is good news for you. It provides a pagination method out of the box. You may be familiar with writing like this:
$comments = Comment::paginate(20);
Using this method, you can paginate the comment model with 20 entries per page. Change this value to define how many items are displayed per page. If nothing is specified, the default value is applied, which is 15.
Suppose you want your comments to appear in multiple places on your website. There are always 30 comments per page. If you have to pass parameter 30 everywhere, that's a problem. Therefore, you can set new default values directly on the model.
protected $perPage = 30;
Add custom values in the model
Eloquent has a powerful feature called "accessor". This feature allows you to add custom fields to the model or tables that do not exist in the model. It doesn't matter if you use an existing value or define a completely new one, you can always fall back. Below is an example of how the accessor works. Suppose there is a model named user
, we add a FullName accessor to it:
function getFullNameAttribute() { return sprintf('%s %s', $this->first_name, $this->last_name); }
Now you can access the full_name
attribute on the post model, as follows :
User::latest()->first()->full_name;
If an object (such as a collection) is returned, this property will not be attached to the user model. Add the protected$appends
attribute to the model. It accepts an array with one or more fields, which should be automatically appended from now on. Just write it like this:
protected $appends = ['full_name'];
Add a mutator (property setter) for the non-existent column
The mutator is the opposite of the getter. You can do really interesting things with it. For example, convert different types of input. Let me tell you in detail. Suppose you want to save a type of time period. Generally, you always save the smallest units possible. In our case it's seconds. For UX reasons, users don't want to enter seconds, like minutes in one place, or hours in another. This can all be resolved quickly.
class Video extends Model { public function setDurationInMinutes($value) { $this->attributes['duration_in_seconds'] = $value * 60; } public function setDurationInHours($value) { $this->attributes['duration_in_seconds'] = $value * 60 * 60; } }
The above code means that you can use a field that does not exist in the data table itself. The
duration_in_minutes field is used in the
model, but in the background, we use duration_in_seconds
to update, or it is possible to use a non-existent field duration_in_hours
. According to this logic, we call it like this in the Controller:
class AnyController { public function store() { $video->update([ 'title' => request('title'), 'duration_in_minutes' => request('duration_in_minutes'), ]); } }
This will save you time in doing calculations in the controller, you can simply use the non-existent column and use ## when performing certain calculations #mutatorMap its result to the correct field.
$comments = Comment::all(); foreach ($comments as $comment) { echo $comment->user->name; }In the above example, we will get all the comment data. Then iterates through the comments and displays the username for each comment. There is nothing wrong with this code and it works fine, but we ran into a problem. Lazy loading now ensures that the query to get the user is only executed when we want to output the username. Welcome to your first N 1 question. Why N 1? N is always the number of reviews and 1 is the query to get the reviews. For example, if we have 500 reviews, then the query to get all reviews is triggered once, and then one query to get the corresponding user-per reviews. So 500 for 1 query. This means that as the number of annotations increases, so does the number of queries. To prevent this, there is a method called eager loading.
$comments = Comment::with('user')->get(); foreach ($comments as $comment) { echo $comment->user->name; }
这会以两个查询结束。第一个查询获取所有注释,第二个查询立即获取所有关联用户。在后台,会发生以下情况(简化版SQL):
SELECT id, user_id, body FROM comments; SELECT name FROM users WHERE user_id IN (1,2,3,4,5...);
不论是 10、500 还是 10000 条评论数据都不重要,我们都依旧只执行两次SQL查询。
好了,你现在已经看到如何使用渴求式加载了。但只限于如何手动使用。你还可以将整个过程自动化,以便某些关联关系总是自动通过渴求式方式加载。为此,需要给模型设定一个属性。
protected $with = [];
我们可以在Comment
model简单设置 protected $with = ['user'];
, 从现在起,user
在任何时候都会自动加载。
我们还有很多种渴求式加载,有仅加载特定列、嵌套即时加载、多个即时加载等等。更多详情请Laravel文档或深入核心。
modelKeys 方法
有的时候需要查询所有的主键 ID, 查询是否复杂并不重要,大多数人可能会像这样做:
User::all()->pluck('id');
这个操作很 nice,但是返回的是一个集合,想要转换成数组的话可以使用 toArray()
。
User::all()->pluck('id')->toArray();
大多数情况下,上面的操作的可以简化成这样:
User::all()->modelKeys();
这种方式返回一个数组。重要的是这个方法并不会总是返回 id
。 顾名思义,他是以数组的形式返回所有模型主键。主键默认是id
,同时也可以在模型中定义主键名。
protected $primaryKey = 'id';
原文地址:https://laravel-news.com/6-eloquent-secrets
译文地址:https://www.php.cn/link/c7decb5ce28209911b545d0b1059c5e3
【相关推荐:laravel视频教程】
The above is the detailed content of 6 Laravel Eloquent tips to help you improve code readability!. For more information, please follow other related articles on the PHP Chinese website!

Laravel stands out by simplifying the web development process and delivering powerful features. Its advantages include: 1) concise syntax and powerful ORM system, 2) efficient routing and authentication system, 3) rich third-party library support, allowing developers to focus on writing elegant code and improve development efficiency.

Laravelispredominantlyabackendframework,designedforserver-sidelogic,databasemanagement,andAPIdevelopment,thoughitalsosupportsfrontenddevelopmentwithBladetemplates.

Laravel and Python have their own advantages and disadvantages in terms of performance and scalability. Laravel improves performance through asynchronous processing and queueing systems, but due to PHP limitations, there may be bottlenecks when high concurrency is present; Python performs well with the asynchronous framework and a powerful library ecosystem, but is affected by GIL in a multi-threaded environment.

Laravel is suitable for projects that teams are familiar with PHP and require rich features, while Python frameworks depend on project requirements. 1.Laravel provides elegant syntax and rich features, suitable for projects that require rapid development and flexibility. 2. Django is suitable for complex applications because of its "battery inclusion" concept. 3.Flask is suitable for fast prototypes and small projects, providing great flexibility.

Laravel can be used for front-end development. 1) Use the Blade template engine to generate HTML. 2) Integrate Vite to manage front-end resources. 3) Build SPA, PWA or static website. 4) Combine routing, middleware and EloquentORM to create a complete web application.

PHP and Laravel can be used to build efficient server-side applications. 1.PHP is an open source scripting language suitable for web development. 2.Laravel provides routing, controller, EloquentORM, Blade template engine and other functions to simplify development. 3. Improve application performance and security through caching, code optimization and security measures. 4. Test and deployment strategies to ensure stable operation of applications.

Laravel and Python have their own advantages and disadvantages in terms of learning curve and ease of use. Laravel is suitable for rapid development of web applications. The learning curve is relatively flat, but it takes time to master advanced functions. Python's grammar is concise and the learning curve is flat, but dynamic type systems need to be cautious.

Laravel's advantages in back-end development include: 1) elegant syntax and EloquentORM simplify the development process; 2) rich ecosystem and active community support; 3) improved development efficiency and code quality. Laravel's design allows developers to develop more efficiently and improve code quality through its powerful features and tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software