Laravel - mongodb: Difference between revisions
From AWVVO
Jump to navigationJump to search
Line 72: | Line 72: | ||
}; | }; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== User class == | |||
<syntaxhighlight lang="php" copy line highlight="0"> | |||
<?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', | |||
]; | |||
} | |||
</syntaxhighlight> |
Latest revision as of 17:57, 5 April 2025
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',
];
}