search
HomePHP FrameworkLaravelDetailed introduction to laravel data migration and Eloquent ORM (code example)

This article brings you a detailed introduction (code example) about laravel data migration and Eloquent ORM. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The database can be said to be the most commonly used and important part of back-end development. Laravel provides a very practical Eloquent ORM model class to interact with the database simply and intuitively. At the same time, data migration is used to manage the database, which can be shared and edited with the team. For more information on both, please see the documentation below.
The following uses both as an example. The requirement is to record user browsing records. Please do not bring this example into actual projects, this article is only an example. The actual project is recorded according to the requirements, and the storage method is selected.

Create a data table

The first step is of course to create a data table. Using the artisan command can easily create models and migrate data. php artisan make:model Models/BrowseLog -m, the -m parameter also creates a data migration file when creating the model. After executing the above command, two new files, app/Models/BrowseLog.php and database/migrations/{now_date}_create_browse_logs_table.php, were added.
Next edit {now_date}_create_browse_logs_table.php to create the data table

/**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('browse_logs', function (Blueprint $table) {
            $table->increments('id');
            $table->ipAddress('ip_addr')->comment('ip 地址');
            $table->string('request_url', 20)->comment('请求 url');
            $table->char('city_name', 10)->comment('根据 ip 获取城市名称');
            $table->timestamps();
        });

        DB::statement("ALTER TABLE `browse_logs` comment'浏览记录表'"); // 表注释
    }

The code is as above. After the editing is completed, execute the command php artisan migrate to create all data tables that have not been migrated. As follows

Detailed introduction to laravel data migration and Eloquent ORM (code example)

Personally, laravel’s default data type is questionable. For example, the data format of ipAddress() is varchar(45). In fact, you can use ip2long to convert it to int for storage. timestamps() can also use timestamps for storage. Of course, laravel also provides accessors & modifiers for easy maintenance. You can choose by yourself in the actual project.

Define middleware

Define a global middleware that will be executed on every request. Execute php artisan make:middleware BrowseLog to create the app/Http/Middleware/BrowseLog.php file.

Add the created middleware to app/Http/Kernel.php as follows

Detailed introduction to laravel data migration and Eloquent ORM (code example)

Record data

Finally, in the middleware, just record the data to the database. The code is as follows

/**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $log = new \App\Models\BrowseLog();

        $log->ip_addr = $request->getClientIp();
        $log->request_url = $request->path();
        $log->city_name = get_city_by_ip();

        $log->save();

        return $next($request);
    }
After accessing several links, go to the database to check

Detailed introduction to laravel data migration and Eloquent ORM (code example)

Data writing is normal, this example ends here.

The above is the detailed content of Detailed introduction to laravel data migration and Eloquent ORM (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
The Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkThe Illusion of Inclusion: Addressing Isolation and Loneliness in Remote WorkApr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel for Full-Stack Development: A Comprehensive GuideLaravel for Full-Stack Development: A Comprehensive GuideApr 25, 2025 am 12:27 AM

Laravelispopularforfull-stackdevelopmentbecauseitoffersaseamlessblendofbackendpowerandfrontendflexibility.1)Itsbackendcapabilities,likeEloquentORM,simplifydatabaseinteractions.2)TheBladetemplatingengineallowsforclean,dynamicHTMLtemplates.3)LaravelMix

Video Conferencing Showdown: Choosing the Right Platform for Remote MeetingsVideo Conferencing Showdown: Choosing the Right Platform for Remote MeetingsApr 25, 2025 am 12:26 AM

Key factors in choosing a video conferencing platform include user interface, security, and functionality. 1) The user interface should be intuitive, such as Zoom. 2) Security needs to be paid attention to, and Microsoft Teams provides end-to-end encryption. 3) Functions need to match requirements, GoogleMeet is suitable for short meetings, and CiscoWebex provides advanced collaboration tools.

What database versions are compatible with the latest Laravel?What database versions are compatible with the latest Laravel?Apr 25, 2025 am 12:25 AM

The latest version of Laravel10 is compatible with MySQL 5.7 and above, PostgreSQL 9.6 and above, SQLite 3.8.8 and above, SQLServer 2017 and above. These versions are chosen because they support Laravel's ORM features, such as the JSON data type of MySQL5.7, which improves query and storage efficiency.

The Benefits of Using Laravel as a Full-Stack FrameworkThe Benefits of Using Laravel as a Full-Stack FrameworkApr 25, 2025 am 12:24 AM

Laravelisanexcellentchoiceforfull-stackdevelopmentduetoitsrobustfeaturesandeaseofuse.1)ItsimplifiescomplextaskswithitsmodernPHPsyntaxandtoolslikeBladeforfront-endandEloquentORMforback-end.2)Laravel'secosystem,includingLaravelMixandArtisan,enhancespro

What is the latest version of Laravel?What is the latest version of Laravel?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

How does the newest Laravel version simplify development?How does the newest Laravel version simplify development?Apr 24, 2025 pm 05:01 PM

ThelatestLaravelversionenhancesdevelopmentwith:1)Simplifiedroutingusingimplicitmodelbinding,2)EnhancedEloquentcapabilitieswithnewquerymethods,and3)ImprovedsupportformodernPHPfeatureslikenamedarguments,makingcodingmoreefficientandenjoyable.

Where can I find the release notes for the latest Laravel version?Where can I find the release notes for the latest Laravel version?Apr 24, 2025 pm 04:53 PM

You can find the release notes for the latest Laravel version at laravel.com/docs. 1) Release Notes provide detailed information on new features, bug fixes and improvements. 2) They contain examples and explanations to help understand the application of new features. 3) Pay attention to the potential complexity and backward compatibility issues of new features. 4) Regular review of release notes can keep it updated and inspire innovation.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools