laravel 8 eloquent UpdateOrCreate ()の例


もともとhttps://codeanddeploy.com訪問し、サンプルコードをダウンロードしてください
この記事では、Laravel EldateOrCreate ()の使用方法とその重要性を説明します.LaraVelはUpdateOrCreate ()を使用して既存のレコードを更新するのを助けます.以下の例については、以下の例を参照してください.

https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-updateorcreate-example 例例47 - 1 laravel update ()の使用例


<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = 'Post 38';
        $description = 'Description for post 38 - updated.';
        $body = 'Body for post 38.';

        $post = Post::where('title', $title)->first();

        if(is_null($post)) {
            $post = new Post([
                'title' => $title,
                'description' => $description,
                'body' => $body
            ]);
            $post->save();
        } else {
            $post->description = $description;
            $post->body = $body;
            $post->update();
        }

        print_r($post);die;
    }
}

例例47 - 1 laravel update ()の使用例


<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::updateOrCreate([
            'title' => 'Post 3'
        ], [
            'description' => 'Description for post 3.',
            'body' => 'body for post 3 - updated.'
        ]);

        print_r($post);die;
    }
}
上記のコードから分かるように、更新または作成のために同じ機能を持っていますが、laravel UpdateOrCreate ()メソッドの実装では、コードを短縮します.
私はこのチュートリアルを助けることを望む.あなたがこのコードをダウンロードしたいならば、親切に をここで訪問してください.
ハッピーコーディング