laravel 8 eloquent firstorcreate ()の例


もともとhttps://codeanddeploy.com訪問し、サンプルコードをダウンロードしてください
このポストでは、Laravel Elquent Create ()の使用方法とその重要性を説明します.LaravelはFirStorCreate ()を提供し、データベースにレコードを見つけようとしていない場合は、新しいレコードを作成して返します.

https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-firstorcreate-example 例例54 - 1 laravel firstorCreate ()の使用例


<?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 3';
        $post = Post::where('title', $title)->first();

        if (is_null($post)) {
            $post = new Post(['title' => $title]);
        }

        $post->description = 'Description for post 3.';
        $post->body = 'Body for post 3.';

        $post->save();

        print_r($post); die;
    }
}


Example with Laravel firstOrCreate()
<?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::firstOrCreate(
            ['title' => 'Post 5'],
            ['description' => 'Description for post 5.', 'body' => 'Body for post 5.']
        );

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