Search code examples
laravelvalidationmodelconnection

Model property connection (validate request) - Laravel


I have identified a validation issue in the controller.

The problem looks like this if you specify a connection in the model, and create validation in the controller. In the validation, specify unique columns, then the model is connected as by default. My code snippets.

Model

protected $connection = 'api';
protected $table = 'pages';

protected $fillable = [
    'name', 'title', 'description',
    'keywords', 'slug', 'content', 'status',
    'sort', 'type'
];

public function sluggable(): array
{
    return [
        'slug' => [
            'source' => 'title'
        ]
    ];
}

Controller (resource)

public function store(PagesRequest $request)
{
    Pages::create($request->all());

    return view('pages.pages.index', [
        'pages' => Pages::orderBy('id', 'desc')->paginate(30)
    ])->with(['success' => true]);
}

PagesRequest

public function rules()
{
    return [
        'name' => 'required|string|min:5|max:255|unique:pages,name,'.@$this->page->id,
        'title' => 'required|string|min:5|max:255|unique:pages,title,'.@$this->page->id,
        'description' => 'required|string|min:5|max:255',
        'keywords' => 'required|string|min:5|max:255',
        'slug' => 'unique:pages,slug,'.@$this->page->id
    ];
}

As I understand it, in the rules method there is a request to the unique: pages database and here the model already works not through the connection, but through the default connection.

If I remove checks for "unique", then everything works.

PagesRequest

public function rules()
{
    return [
        //'name' => 'required|string|min:5|max:255|unique:pages,name,'.@$this->page->id,
        //'title' => 'required|string|min:5|max:255|unique:pages,title,'.@$this->page->id,
        'description' => 'required|string|min:5|max:255',
        'keywords' => 'required|string|min:5|max:255',
        //'slug' => 'unique:pages,slug,'.@$this->page->id
    ];
}

Is there any solution in this situation?


Solution

  • public function rules()
        {
            return [
                'name' => 'required|string|min:5|max:255|unique:api.pages,name,'.@$this->page->id,
                'title' => 'required|string|min:5|max:255|unique:api.pages,title,'.@$this->page->id,
                'description' => 'required|string|min:5|max:255',
                'keywords' => 'required|string|min:5|max:255',
                'slug' => 'unique:api.pages,slug,'.@$this->page->slug
            ];
        }