Search code examples
mysqlmongodbvalidationuniquelaravel-5.3

Base Table not found on unique value validation in MongoDB with laravel


I'm using laravel 5.3 with jenssegers/laravel-mongodb package for managing mongodb connections.

I want to check every time a user send a request to register a website in my controller if it's unique then let the user to register his/her website domain.

I wrote below code for validation but What I get in result is :

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'iranad.seat' doesn't exist (SQL: select count(*) as aggregate from `seat` where `domain` = order.org)

my controller code :

public function store(Request $request) {
    $seat = new Seat();

    $validator = Validator::make($request->all(), [
            'domain' => 'required|regex:/^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/|unique:seat', //validating user is entering correct url like : iranad.ir
            'category' => 'required',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->messages(), 400);
    } else {
        try {
            $statusCode = 200;
            $seat->user_id = Auth::user()->id;
            $seat->url = $request->input('domain');
            $seat->cats = $request->input('category');
            $seat->filter = [];
            if($request->input('category') == 'all') {
                $obj['cats'] = 'false';
                $seat->target = $obj;
            } else {
                $obj['cats'] = 'true';
                $seat->target = $obj;
            }
            $seat->status = 'Waiting';
            $seat->save();
        } catch (\Exception $e) {
                $statusCode = 400;
        } finally {
                $response = \Response::json($seat, $statusCode);
                return $response;
        }
    }
}

My Seat Model :

namespace App;

use Moloquent;
use Carbon\Carbon;

class Seat extends Moloquent {

    public function getCreatedAtAttribute($value) {
        return Carbon::createFromTimestamp(strtotime($value))
            ->timezone('Asia/Tehran')
            ->toDateTimeString();
    }
}

Obviously The validator is checking if domain is unique in mysql tables which causes this error, How can I change my validation process to check mongodb instead of mysql ?


Solution

  • I solved the problem, The solution is that you should add Moloquent to your model and define database connection :

    namespace App\Models;
    
    use Moloquent;
    use Carbon\Carbon;
    
    class Seat extends Moloquent
    {
        protected $collection = 'seat';
        protected $connection = 'mongodb';
    }