Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AmineBHD's avatar

Query Builder with Model Attributes

I'm Using Query Builder, and I would like to use setters in my model, how can I do it please

This is my code :

$tenantUser = DB::connection('tenant')->table('users')->insert($request->validated());

the password method, doesn't work because i'm using query builder:

protected function password(): Attribute
{
    return Attribute::make(
        set: fn ($value) => Hash::make($value)
    );
}
0 likes
9 replies
jlrdw's avatar

Don't use query builder, use eloquent. Eloquent has all of query builder methods as well.

1 like
AmineBHD's avatar

@SilenceBringer "Non-static method Illuminate\Database\Eloquent\Model::setConnection() cannot be called statically",

jlrdw's avatar

@AmineBHD I have answered this in past: https://laracasts.com/discuss/channels/laravel/dbconnection-does-not-work-as-documented

But:

For eloquent

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Powner extends Model
{

    protected $table = 'dc_powners';
    protected $primaryKey = 'ownerid';
    protected $connection = 'mysqlv2';   <-----------------
    protected $fillable = [
        'ownerid',
        'oname',
        'ostreet',
        'odate',
        'ocheck'
    ];
    public $timestamps = [];

}

1 like
AmineBHD's avatar
AmineBHD
OP
Best Answer
Level 1

// $tenantUser = DB::connection('tenant')->table('users')->insert($request->validated());

    $tenantUser = User::on('tenant')->create($request->validated()); // for static usage
jlrdw's avatar

@AmineBHD Your answer allows:

protected function password(): Attribute
{
    return Attribute::make(
        set: fn ($value) => Hash::make($value)
    );
}

?

Or does using eloquent allow that? It is two different questions. You asked about accessors and mutators, so I don't follow the answer you showed?

Please or to participate in this conversation.