Laravel: two models in one controller method - laravel

Let me explain about my problem.
I am currently using Laravel 5.0. Here is my structure
Table: bgts, Model: Bgt, Controller: BgtController
Table: bgthistories, Model: BgtHistory
Now I want to do these:
Everytimes creating new item into bgts table, I want to make a copy and insert into bgthistories table. Then, everytimes that record is updated, i'll copy one more version, still insert into bgthistories.
Here is store() method.
public function store(Request $request) {
$bgt = new Bgt();
$history = $this->coppy($bgt);
$uploader = new UploadController('/data/uploads/bgt');
$bgt->name = $request['name'];
$bgt->avatar = $uploader->avatar($request);
$bgt->attachments($uploader->attachments($request));
//dd($bgt);
$bgt->save();
$history->save();
return redirect('bgt');
}
And this is the coping:
public function coppy($bgt) {
$array = $this->$bgt->toArray();
$version = new BgtHistory();
foreach($array as $key => $value) {
$version->$key = $value;
}
return $version;
}
I create migration tables already. Everything is ready. But, when I call
$bgt->save();
$history->save();
It did not work. If I remove $history->save();, it create new record ok. I think the save() method that built-in in Model provided by Laravel is problem. Can anyone tell me how to solve this.
I tried to build the raw query then executed it by DB:statement but it did not work too. Every try to execute anything with DB is failing.

Please research before re-inventing the wheel.
(Same stuff different sites in case one is down)
http://packalyst.com/packages/package/mpociot/versionable
https://packagist.org/packages/mpociot/versionable
https://github.com/mpociot/versionable
Cheers and good luck ;)

Related

The Laravel $model->save() response?

If you are thinking this question is a beginner's question, maybe you are right. But really I was confused.
In my code, I want to know if saving a model is successful or not.
$model = Model::find(1);
$model->attr = $someVale;
$saveStatus = $model->save()
So, I think $saveStatus must show me if the saving is successful or not, But, now, the model is saved in the database while the $saveStatus value is NULL.
I am using Laravel 7;
save() will return a boolean, saved or not saved. So you can either do:
$model = new Model();
$model->attr = $value;
$saved = $model->save();
if(!$saved){
//Do something
}
Or directly save in the if:
if(!$model->save()){
//Do something
}
Please read those documentation from Laravel api section.
https://laravel.com/api/5.8/Illuminate/Database/Eloquent/Model.html#method_getChanges
From here you can get many option to know current object was modified or not.
Also you can check this,
Laravel Eloquent update just if changes have been made
For Create object,
those option can helpful,
You can check the public attribute $exists on your model
if ($model->exists) {
// Model exists in the database
}
You can check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$model->id){
App::abort(500, 'Some Error');
}

In Laravel, how do you bind parameters in DB raw query when you set model attribute?

For example, I have my codes.
$news = new News();
$news->title = 'hello world';
$new->user = $user_id,
$news->urlcc = DB::raw('crc32("'.$args['newsShortUrlInput'].'")');
$news->save();
$news->refresh();
Here with attribute $news->urlcc comes from user input after using mysql function crc32();
For the SQL injection issue, above codes not safe.
So, my question is how to bind the parameters in DB::raw() with Laravel model something like below.
$news->urlcc = DB::raw('crc32(:newsShortUrlInput)', ['newsShortUrlInput' => $args['newsShortUrlInput]);
Thanks,
I found one solution, not sure it is right or perfect solution.
In News model class to rewrite setAttribute, see below.
public function setUrlcrcAttribute($shortUrl)
{
$this->attributes['urlcrc'] = $this->getConnection()->select('select crc32(?) as urlcrc', [$shortUrl])[0]->urlcrc;
}
In your service class to create a new model like below.
$news = new News();
$news->title = 'hello world';
$new->user = $user_id,
$news->urlcrc = $args['newsShortUrlInput']; // Laravel model will try to build the real attribute urlcrc
$news->save();
$news->refresh();
It works to me, but not sure this is perfect solution or not.

Modify Laravel request before insert

Is is possible to modify a request before it gets inserted into the database?
public function store(StoreRequest $request)
{
$request->date_posted = strtotime($request->date_posted);
//insert data here.
}
Yes it can be, what you have works perfectly fine
public function store(StoreRequest $request)
{
$request->date_posted = strtotime($request->date_posted);
or
$datePosted = $request->date_posted + 2;
$datePosted = $request->date_posted . 'some other addons';
//insert data here.
}
these are just examples but i hope you get what im saying.
Fyi if you input into the db, the created_at and updated_at will update and so you don't need to insert the time the post was made manually.
Try this solution maybe can resolve your issue . Add setter in model so it will be look like this
Class ModelX {
public function setDateDatePosted Attribute($date_posted)
{
$this->attributes['date_posted'] = strtotime($date_posted);
}
}
hope it useful for you .

Joomla 3.x how to delete the data using an object

In joomla 3.x implemented delete the data from database using object
this my code not working
function deleteJob()
{
$id = $_REQUEST['id_ud'];
$object = new stdClass();
$object->id = $id;
$resultd =JFactory::getDbo()->deleteObject('#___institute_post_job',$object, 'id');
}
if(isset($_POST['inidelete_job'])) {
deleteJob();
}
please help me?
There is No method for "deleteObject" . if you want to delete operation , you have write query and execute.
There is no object delete just like insertObject,updateObject,...
refer last example for delete:
https://docs.joomla.org/Inserting,_Updating_and_Removing_data_using_JDatabase
JFactory::getDBo() basically call JDatabaseDriver,you can use following methods.
https://api.joomla.org/cms-3/classes/JDatabaseDriver.html

How to acces is_* property in laravel model?

I am working with laravel 4.2 and have table in db with property is_active.
When I try to access this model property:
$model->is_active
I am getting following error:
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
So question is how to access this property?
Please do not recommend to rename this field in the database if possible because this is already existing database in production.
Here is my model class:
class Position extends \Eloquent {
protected $table = "hr_positions";
protected $fillable = ['slug', 'info_small', 'info_full', 'is_active', 'start_date', 'end_date', 'tags', 'user_create_id', 'user_update_id'];
use \MyApp\Core\StartEndDateTrait;
public function postulations(){
return $this->hasMany('Postulation', 'position_id', 'id');
}
}
Latest notice:
All this error ocurrs on a page where I am creating my entity. In the controller before forwarding to the page I am doing:
$position = new \Position();
and then, for example, following code produce error as well:
dd(($position->getAttribute('is_active')));
but if I replace $position = new \Position(); with
$position = \Position::first();
error is gone?
What is going on here?????
Laravel does a lot of magic behind the scenes, as in, calls a lot of php magic methods.
If a called property is not defined, __call is invoked which in Eloquent calls getAttribute().
Steps taken by getAttribute($key) are
Is there a database field by this key? If so, return it.
Is there a loaded relationship by this key? If so, return it.
Is there a camelCase method of this key? If so, return it. (is_active looks for isActive method)
Returns null.
The only time that exception is thrown is in step 3.
When you create a new instance, eloquent has no idea what kind of fields it has, so if you have a method by the same name, it will always throw a relation error, this seems to be the case in both Laravel4 and Laravel5.
How to avoid it? Use the getAttributeValue($key) method. It has no relation checks and returns null by default.
Alternatively you can also add a get mutator for your field.
I have found a hack for this. Still not ideal but at least I have some solution. Better any than none.
So This code produce problem:
$position = new \Position();
if($position->is_active){
//
}
and this one works fine, this is solution even hacky but solution:
$position = new \Position(['is_active' => 0]);
if($position->is_active){
//
}
I will wait if someone give better, cleaner solution. If no one comes in next few days I will accept mine.

Resources