I have a strange problem. I'm trying to update a database entry with the save function, but the changed columns only update sometimes but most times they do not change yet I don't get any errors.
This is the code in my update function:
public function editadvocatedetails(Request $request){
try {
##get original data
$oldclaimantdets = Clthirdparties::where('claimant_code',$request->claimant_code)->first();
// ##get new data
$claimant_dets = Clthirdparties::where('record_type',$oldclaimantdets->record_type)->where('code',$oldclaimantdets->code)->first();
$claimant_dets->name = $request->name;
$claimant_dets->record_type = $request->record_type;
$claimant_dets->claimant_type = $request->claimant_type;
$claimant_dets->e_mail=$request->e_mail;
$claimant_dets->id_no=$request->id_no;
$claimant_dets->pin_number = $request->pin_number;
$claimant_dets->mobile = $request->mobile;
// // dd($claimant_dets);
$claimant_dets->save();
// dd($claimant_dets);
$mm = $claimant_dets->getChanges();
$user = Auth::user()->user_name;
$process = 'Update Claimant Details';
$claimant_code = $request->claimant_code;
$yy = $this->log_data($mm,$claimant_dets,$user,$process,$claimant_code);
Session::flash('success,'.$request->name.' details has been updated');
return redirect()->back();
} catch (\Throwable $th) {
Session::flash('error,'.$request->name.' failed to be updated');
return redirect()->back();
}
}
My Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
}
When I print the values before the save, I get the correct values for both the old and new data.
It looks like the save() doesn't execute. The redirect is executed.
I'm aware of the update() method, but I used this way for updating entries in my database a lot and until now I never had any problems and I don't get where the problem is.
In the meantime I have reverted to update() to run the update query to solve the problem. But I still want to know why it is happening?
Maybe someone has an idea?
Sometimes hmm..., save() method is formally dependent on $fillable attribute array in the model. So, try defining fillable attributes.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Clthirdparties extends Model
{
protected $connection = 'oracle';
protected $table='clthirdparties';
public $timestamps=false;
public $keyType = 'string';
public $primaryKey='claimant_code';
public $incrementing=false;
protected $guarded = [];
protected $fillable = ['name','record_type','claimant_type','e_mail','id_no','pin_number','mobile',] ; //include all your attributes here.
}
Related
I've got the following function in a migration file. The migration is to add a new column, and then update the columns of the existing entries:
<?php
private function updatePlans()
{
$plans = PlanProvider::query()->get();
foreach ($plans as $plan) {
$plan->num_adults = 1;
if (stripos($plan->rate_name, 'couple') !== false) {
$plan->num_adults = 2;
}
$plan->save();
}
}
Now, what's happening here is that when I call save(), it's updating EVERY model, instead of the one inside the loop. I have a similar function for another migration, and it works as expected. Why would this update every model rather than just the one?
$plans is a Collection that contains all your "plans".
Your $plan->save(); is outside your if conditions, so obviously it updates every single row, no matter if it has 1 or 2 num_adults
public function store(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:subscribers'
]);
$subscriber = new Subscriber();
$subscriber->email = $request->email;
$subscriber->save();
Toastr::success('You are Successfully Added Our Subscriber List:)','Success');
return redirect()->back();
}
you can try this
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class PlanProvider extends Model
{
protected $table = 'plan_provider';
protected $guarded = [];
public $timestamps = false;
}
private function updatePlans()
{
$plans = PlanProvider::findOrFail(id);
$plans->num_adults = 1;
$plans->save();
return redirect()->back();
}
I need to guard the ID column when inserting into a database, however I don't want to guard it when inserting into a different database due to needing to manually set the ID, so that the tables are in sync.
However I can't figure out a way to do it, below is what I have got at the moment, however this doesn't work at all as I just get an error:
Field 'id' doesn't have a default value
This is my current model:
<?php
namespace App\Models\Seasonal;
use Illuminate\Database\Eloquent\Model;
class SeasonalBanner extends Model
{
protected $connection = 'dev';
protected $guarded = [ 'id' ];
protected $appends = [ 'period' ];
public static function boot()
{
parent::boot();
self::creating(function($model){
if ($model->connection === 'live') {
$model->guarded = [];
}
});
}
public function dates() {
return $this->hasMany(SeasonalBannerDates::class);
}
public function getPeriodAttribute() {
return [ $this->start, $this->end ];
}
}
The best way in my opinion is not to use $guarded at all in such case. Just set:
protected $guarded = [];
and in your code depending on which database you use, either fill id or not.
in this code as:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->take(5);
which that work fine i want to use inRandomOrder() to get random rows from contents, Contents and ContentCategories are belongsToMany RelationShips and this code:
$latestHerbsInformation = \App\ContentCategories::find('14')->contents->inRandomOrder()->take(5);
don't work for me.
Contents model:
class Contents extends Model
{
use Sluggable;
protected $table = 'contents';
protected $guarded = ['id'];
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
}
ContentCategories model:
class ContentCategories extends Model
{
protected $table = 'contents_categories';
protected $guarded = ['id'];
public function contents()
{
return $this->belongsToMany(Contents::class);
}
}
i get this error:
Method inRandomOrder does not exist.
how can i solve this problem? Thanks in advance
The correct query is:
\App\ContentCategories::find('14')->contents()->inRandomOrder()->take(5)->get();
Because this will execute the query and will return a collection:
\App\ContentCategories::find('14')->contents
I have a User-Roles model, using Laravel 4 where a user can have many roles, using Eloquent. I can access all roles linked to a user easily using this code :
class User extends Model {
protected $table = 'user';
protected $fillable = array('name');
public function rolesLinked() {
return $this->hasMany('App\UserRoleLink', 'user_id');
}
}
I've been trying to obtain the roles that are not linked to a user, to display on the specific user's page in a select box. Using this function, included in the User class.
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('App\UserRoleLink',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
The problem is, calling this function gives me the following error.
Call to undefined method Illuminate\Database\Query\Builder::App\UserRoleLink()
I've tried using has with < 1 to see if the function was problematic, but after reading this and the online source code, the function call pretty much does what I've tried.
Is something wrong in my function call, or have I messed up configurations somewhere?
For reference, here are my other Model classes:
class UserRoleLink extends Model{
protected $table = 'user_role_link';
protected $fillable = array('role_id','user_id);
public function role() {
return $this->hasOne('App\Role', 'role_id');
}
}
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
}
EDIT: I've found out that I messed up by fillables when I copy-pasted. It didn't fix the issue, but I guess that's one step closer.
To use whereDoesntHave method, you must add the relation in your Role Model.
class Role extends Model{
protected $table = 'role';
protected $fillable = array('name');
public function UserRoles() {
return $this->hasMany('App\UserRoleLink', 'id');
}
}
Also, the whereDoesntHave method first parameter is not thte model but the function of the relation:
public function rolesNotLinked() {
$user = this
$roles = Roles::whereDoesntHave('UserRoles',function($query) use ($user){
$query->where('user_id',$user->id);
});
}
I am using Laravel 4 and eloquent orm to build a movie session database.
Now I have the following Models.
class Location extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_location';
protected $fillable = array('name', 'desc');
public function sessions(){
return $this->hasMany('Session', 'location_id');
}
}
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->hasOne('Location', 'id');
}
}
(Note: These models are stripped to the necessary code.)
Now in my controller, I have the following.
$Sessions = Session::all();
foreach($Sessions as $Session){
echo (isset($Session->location->name) ? $Session->location->name : 'NO LOCATION');
}
And this is what my database looks like:
Now, everything seems to work, but even though both sessions have the same location, ONLY the first session will return the name of the location! The second echo will return "NO LOCATION".
Any idea or help as to why would be appreciated. If this answer isnt clear enough let me know.
Try this one in place of yours:
class Session extends \Eloquent
{
public $timestamps = false;
public $table = 'movsys_session';
protected $fillable = array('time');
public function location(){
return $this->belongsTo('Location');
}
}