I have below code that fetches users and relational role object for each user.
$query = (new UserModel())->newQuery();
$query->with("Role");
$data = $query->get(["UserName", "EmailAddress", "User_ID"]);
I have 3 roles present in database and they are in cache.
Is there any way to change this line of code: $query->with("Role"); such that while fetching the users each time, it will not need to fetch roles from database.
Maybe you can hook into the Retrieved event from Eloquent. When retrieving the model from the Database you can fetch the role from the cache and set it on the model. Perhaps that could be a solution for you?
Take a look at the Laravel Docs on eloquent events here: https://laravel.com/docs/5.6/eloquent#events
Maybe this will work out something for you, add this to your model class:
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::retrieving(function ($user) {
$user->fetchFromCache("Role"); //replace this line with however you could fetch it from the cache
});
}
Related
I'm new into Laravel and I'm trying to store the user's company id on a column of the products table each time a user creates a new product. The company's id it's retrieved from the user's session. I'm trying it with Laravel's Mutator:
public function setFirstNameAttribute($value) {
$this->attributes['company_id'] = session()->get('company.id');
}
But each time I create a new Product the company id stored it's null. Seems like the function it's never executing. Is there any other resource to perform actions like this?
You must use model events - this will be executed on model creation before saving. Or you can use another events depends on you logic - see docs.
class YourModel extends Model
{
/**
* The "booted" method of the model.
*
* #return void
*/
protected static function booted()
{
static::creating(function (YourModel $model) {
$model->company_id = session()->get('company.id');
});
}
}
Mutators only works when you change mutating field directly:
$model->first_name = 'new_name'
And with your code - you will lost "new_name".
I noticed that the function name is incorrect, since the accessors use "studly" cased name of the column you wish to access, it may be as simple as to change
public function setFirstNameAttribute($value)
to
public function setCompanyIdAttribute($value)
I'm trying to merge current user id with with a laravel $request and aftr merging all data will be saved into DB. After execution data save into DB but id save as a null value. Please see my code
public function store(Request $request, ClassModel $model)
{
$model->create($request->merge(['created_user_id' => Auth::user()->id])->all());
return redirect()->route('class.index')->withStatus(__('Class successfully created.'));
}
Can anyone tell me why user id dont save in DB.
Your field is probably nullable but then in your $fillable array of the model (which is used for mass assignment protection), you forgot to include the created_user_id column. Please check that.
I have two models - User and Announcement, and they exist on two separate connections - mysql and intranet respectively. The User model hasMany Announcements and the Announcement belongsTo a single User.
In the Announcement model I have protected $connection = 'intranet' and in the User model I have protected $connection = 'mysql'. Originally I wasn't specifying the $connection property on the User model as it is the default for the application but added it in for testing.
Doing any sort of query works normally. As an example these work:
User::find(1)->announcements()->where('name', 'something')->get()
Announcement::find(2)->user
However, when using whereHas on the Announcements model I get the following SQL Error: Base table or view not found: 1146 Table 'intranet.associate' - associate being the User's table and intranet being the database connection specified in the Announcement model.
While I did find an answer to the question here. I am curious, though, as to why you're required to use ->from(..). Is this intended functionality? I could not find anything in the documentation about using from().
As a side note I was able to fix this "issue" by assigning the $table property in the __construct method in the User model:
__construct(array $attributes = []) {
$this->table = env('DB_DATABASE').'.associate';
}
env('DB_DATABASE') being the default connection's database.
I'm using Laravel 5 and I created a resource controller, setup routing and setup my database model.
My question is: when I do a POST, my store method is called on the controller but how can I take the request data and insert a new entry in the db without having to explicitly set every field?
Here's my code:
public function store(Request $request)
{
$data = $request->all(); // this grabs all my request data - great!
$user = new User;
$user-> ??? // insert ALL posted data
$user->save();
}
I understand that I can do...
$user->name = $request->name;
...for every field. But can someone tell me how to insert everything?
I realize I can probably do a foreach but I'm wondering if there's something better.
There is method fill in every model https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_fill:
$user->fill($request->all());
Eventually you can use create:
\User::create($request->all());
This above is called mass asignment and there is section about this in Eloquents documentation https://laravel.com/docs/5.1/eloquent
You need to define which keys might be set:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// The attributes that are mass assignable
protected $fillable = ['name', 'login', 'birthdate'];
}
I have two databases ("internal" and "external") and I would like to create a BelongsToMany relation between them. The problem, how do I specify in which database the relation_table is stored?
In my current case, I have some users that I would like to connect to some objects from an external database.
User:
public function objects() {
return $this->belongsToMany('\App\Object', 'user_object_relation');
}
Object:
protected $connection = 'mysql_data';
protected $table = 'objects';
protected $primaryKey = 'ObjectID';
Eloquent now is assuming my user_object_relation table in the mysql_data (external) database, however I've created this in the "internal" database.
Q: How do I tell eloquent that the relation table is not in the external table?
// edit:
with return $this->belongsToMany('\App\Object', 'internal.user_object_relation');, I receive an access denied error because the "external" database user has no access to the internal ;)