Model Create Method Not Working - laravel-5

I've the following line of code to determine whether a record exists in the DB, if it does then update it accordingly, if not create it:
$test = Result::where('match_id','=',$input['id'])->get();
if(empty($test)){
Result::create($result);
} else {
Result::where('match_id','=',$input['id'])->update($result);
};
return redirect('admin/results');
The update section works just fine, however the create element doesn't seem to work. When I strip down and just use create it works fine, so can't figure out the problem

You must set your attributes as fillable in your model:
protected $fillable = ['a','b'];
And there is a better way:
Result::updateOrCreate(['match_id'=>$input['id']], ['a'=>$input['a'],'b'=>$input['b']])

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');
}

OctoberCMS get id of component being saved

I am trying to update a table with the path of the uploaded file so that it is easy to email a download link but I cannot seem to get the id.
My component looks like this:
public function onAddJob() {
$manual = new Job();
$manual->company = Input::get('company_name');
$manual->ordered_by = Input::get('client_name');
$manual->ordered_by_email = Input::get('client_email');
$manual->emergency_no = Input::get('emergency_no');
$manual->instructions = Input::get('instructions');
$manual->project_name = Input::get('project_name');
$manual->fileupload = Input::file('fileuploader');
$manual->save();
$this->id = $this->property('id');
Db::table('manual_jobs')->where('id', $this->id)->update(['path' => $manual->fileupload->getPath()]);
Everything saves fine but path is not updated as I am not getting the id correctly, can anyone help show me where I am noobing?
The id component is defined by the variable $primaryKey on the model
default the primary key is 'id' corresponding to a database table field named id
You can overwrite the default keyname by setting $primaryKey to another key
class Foo extends Model {
$primaryKey = 'foo_id';
}
Why i'm explaining this is because you don't need to know the name of the field.
What you can do is:
$foo = new Foo();
$foo->bar = 'baz';
$foo->save();
echo $foo->getKey();
echo $foo->getAttribute($foo->getKeyName());
echo $foo->{$foo->primaryKey}
They will all print out the newly created primary key on the object.
getkey() returns the value of the primary key.
getKeyName() returns the name of the primary key field defined in the model
The solution was a lot simpler than I thought.
What I was looking for was this:
$manual->id
So the update query looks like this:
Db::table('manual_jobs')->where('id', $manual->id)->update(['path' => $manual->fileupload->getPath()]);
Its because when you call ajax request it will not call pageCycle.
as a result your code in page will not executed.
your code on page may be look like this one
{% component 'yourComponent' id=someID %}
but this code is not executed during ajax call
to execute page code during ajax call you need to explicitly call $this->controller->pageCycle()
so new code will look like
public function onAddJob() {
// we are calling page code explicitly
$this->controller->pageCycle();
$manual = new Job();
$manual->company = Input::get('company_name');
$manual->ordered_by = Input::get('client_name');
... other code
}
refer this answer as well
Link : OctoberCMS. Variable disappears after ajax request
if you still find issue please comment.

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.

Laravel: two models in one controller method

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 ;)

How to override save() method in a component

Where and how I am overriding the save method in Joomla 3.0 custom component ?
Current situation:
Custom administrator component.
I have a list view that displays all people stored in table.
Clicking on one entry I get to the detailed view where a form is loaded and it's fields can be edited.
On save, the values are stored in the database. This all works fine.However, ....
When hitting save I wish to modify a field before storing it into the database. How do I override the save function and where? I have been searching this forum and googled quiet a bit to find ways to implement this. Anyone who give me a simple example or point me into the right direction ?
Thanks.
Just adding this for anyone who wants to know the answer to the question itself - this works if you explicitly wish to override the save function. However, look at the actual solution of how to manipulate values!
You override it in the controller, like this:
/**
* save a record (and redirect to main page)
* #return void
*/
function save()
{
$model = $this->getModel('hello');
if ($model->store()) {
$msg = JText::_( 'Greeting Saved!' );
} else {
$msg = JText::_( 'Error Saving Greeting' );
}
// Check the table in so it can be edited.... we are done with it anyway
$link = 'index.php?option=com_hello';
$this->setRedirect($link, $msg);
}
More details here: Joomla Docs - Adding Backend Actions
The prepareTable in the model (as mentioned above) is intended for that (prepare and sanitise the table prior to saving). In case you want to us the ID, though, you should consider using the postSaveHook in the controller:
protected function postSaveHook($model, $validData) {
$item = $model->getItem();
$itemid = $item->get('id');
}
The postSaveHook is called after save is done, thus allowing for newly inserted ID's to be used.
You can use the prepareTable function in the model file (administrator/components/yourComponent/models/yourComponent.php)
protected function prepareTable($table)
{
$table->fieldname = newvalue;
}

Resources