Answer the question
In order to leave comments, you need to log in
How to make private fields in laravel?
Hello, I've been sitting here for 4 hours now, breaking my head, please help.
I need to make some fields in the model private. but neither mutators nor magic methods like __call and __set help me.
I was delighted I thought I found a solution and wrote Trait.
<?php namespace Shohabbos\Express\Traits;
use Exception;
trait Privatable
{
/**
* @var array List of attribute names which should be private.
*
* protected $private = [];
*/
// public function __get($fieldName) {
// $this->isPrivate($fieldName);
// return parent::__get($fieldName);
// }
public function __set($fieldName, $value) {
$this->isPrivate($fieldName);
return parent::__set($fieldName, $value);
}
public function isPrivate($fieldName) {
if (in_array($fieldName, $this->unsettable)) {
throw new Exception('The '.$fieldName.' property is private');
}
}
}
Answer the question
In order to leave comments, you need to log in
This is because you are trying to do something that you don’t understand, but you read in a smart book / article, you saw on YouTube.
jedi mode / No need to make fields private in your model .
Do not try to do what you do not understand, in 5 years it will be clear, but for now, do as it is written in the docks, about simple.
And take out business logic in separate classes. Until you start writing Boeing software, that's enough for you.
And if it’s so important to write everything true, then you should immediately remove the lara, download symphonies and try to overcome it there.
UPD As comrade vism correctly noted, I wrote a little nonsense here out of inertia. Didn't look where I posted the link. There, in the example, the main problem is that the person from the repository again returns the elokuent model itself, but it would be nice to have DTO - Data Transfer Object. Check out the package from Spatie https://github.com/spatie/data-transfer-object .
In general, it would be easier to answer your question if the context was clear. Why private fields? Perhaps it's easier to translate everything into your data, and transfer this "protection" logic to the validation level. Then you don’t need to put anything, just in the validation, where necessary, check the incoming data and throw an error. There will be flexibility here (where you need different controllers) and the "magic" of Laravel as a whole remains boxed.
/---
This is because Laravel uses Eloquent as its ORM, which is based on the ActiveRecord pattern. Many consider it an anti-pattern. Let's leave the srachi outside the framework. Implementing the repository pattern
approach is good for you .
Here is a simple example, it will be clear where to dig and how to act: https://www.twilio.com/blog/repository-pattern-in-...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question