Laravel - mongodb

From AWVVO
Jump to navigationJump to search

Install mongodb dependency

composer require mongodb/laravel-mongodb

Settings in .env

MONGODB_URI="mongodb+srv://..."
MONGODB_DATABASE="demo"
DB_CONNECTION=mongodb

Model

<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class Film extends Model
{
    //protected $connection = 'mongodb';
    protected $table= 'films';
    protected $fillable = [
        'title',
        'year',
        'genre',
        'director',
        'actors',
        'plot',
        'poster',
        'rating'
    ];
}


Create unique index

<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use MongoDB\Laravel\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    protected $connection = 'mongodb';

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('processes', function (Blueprint $collection) {
            $collection->unique(['name'], 'unique_name');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('processes', function (Blueprint $collection) {
            $collection->dropIndex('unique_name');
        });
    }
};


User class

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use MongoDB\Laravel\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $connection = 'mongodb';
    protected $table = 'users';
    protected $fillable = [
        'name',
        'email',
        'password',
    ];
    protected $hidden = [
        'password',
        'remember_token',
    ];
}