Laravel builder - specify a connection on the builder object - laravel

I have an eloquent query builder in Laravel
$builder = Model::orderBy('created_at', 'DESC');
I want to specify a connection to use, because I have a separate db for some data - let's call it 'archive' for example.
Now, I know I can do it statically, like $builder = Model::connection('archive'); [edit] ::on('archive'); apparently
But if I already have the $builder object, and can't use the static function, how can I do it on the builder object?
I've tried
$builder->connection('archive');
$builder->onConnection('archive');
$builder->setConnection('archive');
And these are all failing for me.

There are two solutions.
Define in class
class MyModel extends Model {
protected $connection= 'archive';
protected $table = 'table_name';
}
In a query
(new MyModel())->on('archive')->get();

Related

Laravel Eloquent Get Method Does Not Work

Well, I'm trying to get some records from db with models. My model is like this:
class People extends Model
{
protected $connection = 'test-connection';
protected $table = 't_people';
}
And I'm trying to get them like this:
public function searchPopularPlayers() {
return People::where('popularity', '<=', 10)->get();
}
When I use first() instead of get(), I get the first record. But I need them all. I get null when I use get(). Any help??

Multiple Where Clause in Eloquent & Laravel

Trying to do a multiple select statement with eloquent.
used the Blog::where()
... function, and included an array in it.
$matchThese = ['title' => post('title'), 'slug' => post('slug')];
return Blog::where($matchThese)->get();
When tested it returns an empty value even for matching inputs, database table names correctly written
Model extends October CMS Model, so all eloquent methods in laravel are include. Blog Model Below
<?php namespace Andre\Blogroutes\Models;
use Model;
use ModelNotFoundException;
class Blog extends Model
{
use \October\Rain\Database\Traits\Validation;
public $table = 'blog';
}
Both of the following queries are exactly the same:
$matchThese = ['title' => post('title'), 'slug' => post('slug')];
return Blog::where($matchThese)->get();
and
return DB::table('blog')->where('title', '=',post('title'))->where('slug','=', post('slug'))->get();
if one worked and others didn't that means your Blog model is not actually targetting the right table blog. You should add the following line to you Blog model and see if the old query works:
protected $table = 'blog';
Also inside your controller, do not forget to add:
use App\Blog;
on top of it. Give the old query a roll and see if that works.
Was able to fix this:
DB::table('blog')->where('title', '=',post('title'))->where('slug','=', post('slug'))->get();
The $table variable must be protected not public
public $table = 'andre_blog';
to
protected $table = 'andre_blog';

Laravel 5.5 issue in fetching data through eloquent model

The database table is : prefix_adminUsers and I have a model in UserAdmin.php as below:
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class UserAdmin extends Model
{
protected $table = 'adminUsers';
public $timestamps = false;
}
When I tried to access the same by controller it show me the error:
Illuminate\Database\Eloquent\Builder Object ( [query:protected] =>
Illuminate\Database\Query\Builder Object ( [connection] =>
Illuminate\Database\MySqlConnection Object ( [pdo:protected] => PDO
Object
my controller is as follows:
use App\Model\UserAdmin;
$userRecord = UserAdmin::where('id', '=', Auth::user()->id);
print_r($userRecord);
It's not an error, you are printing the eloquent class Builder, used to build the queries to retrieve the model data, but it doesn't give you the results yet because you are missing ->get() at the end.
Your code should look like:
use App\Model\UserAdmin;
$userRecord = UserAdmin::where('id', '=', Auth::user()->id)->get();
print_r($userRecord);
You can read more how to retrieve Models on the Laravel 5.5 docs.
Since each Eloquent model serves as a query builder, you may
also add constraints to queries, and then use the get method to
retrieve the results.

Laravel 5.3 soft deletes not working when defining a constructor for the model

I have a model Test as follows
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Test extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function __construct() {
if (!\App::environment('production')) {
$this->table='test_stage';
}
}
I have made sure that there is a 'deleted_at' column in my test_stage table. But the soft deletes are not working. Using the delete() method permanently removes the record from the table. As an additional step of verification I manually added 'deleted_at' value for some columns. But query the model still gives me the soft deleted record.
Moreover, removing the model constructor entirely and simply defining the table name using:
protected $table = 'test_stage';
Works like a charm! That is soft deletes magically start working again.
Or is there any way around to define the table name according to the environment without the need of defining a constructor?
I think the problem could be that you're overwriting the constructor, which is set in Illuminate\Database\Eloquent\Model. Have you tried
public function __construct(array $attributes = []) {
parent::__construct($attributes);
if (!\App::environment('production')) {
$this->table='test_stage';
}
}
Edit: more detailed explaination
As you overwrite the constructor of the class you're extending, the original does not get executed anymore. This means necessary functions for the eloquent model do not get executed. See the constructor for Illuminate\Database\Eloquent\Model below:
/**
* Create a new Eloquent model instance.
*
* #param array $attributes
* #return void
*/
public function __construct(array $attributes = [])
{
$this->bootIfNotBooted();
$this->syncOriginal();
$this->fill($attributes);
}
By making sure the extending class requires the same parameters for the constructor as the extended class and executes parent::__construct($attributes); first, the constructor of the extended class gets executed first. After which you can overwrite $this->table in the extending class.

Eloquent save() throws internal server error

I'm building some API app using Slim3 and Eloquent as ORM for model, and having some strange issue.
When I save model, I get internal server error, and can't catch error at all.
My model have only two columns, id pk autoincrement and name (string 255)
this is my settup:
Model:
class Version extends Illuminate\Database\Eloquent\Model
{
protected $table = 'version';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
protected $hidden = ['id'];
}
Action:
public function create(RequestInterface $request, ResponseInterface $response)
{
$params = $request->getParsedBody();
$class = $this->model; //fully namespaced class name
$model = new $class();
$model->fill($params);
return $model->save() ?
$this->success($response, "{$this->getModelName()} successfully saved.") :
$this->error($response, $model->errors());
}
I manager to localize issue to this part of code in Illuminate\Database\Eloquent\Builderline #1242
if (in_array($method, $this->passthru)) {
return call_user_func_array([$this->toBase(), $method], $parameters);
}
But I have no idea what is wrong
EDIT:
I'm using PHP/7.0.0-dev and Slim 3.1
Is Eloquent PHP 7 compatible?
Your Model is a Eloquent Model so to create you can use following code
$version = App\Version::create(['name' => 'Your version name']);
This will remove all the unnecessary functions, and keept yuor code clean.
In your case make sure the $request->getParsedBody();
returns the correct format for Eloquent to use it.

Resources