I have the following code:-
$token = encrypt($guuid);
$tokenDetail = AdminConfig::select('config_value')
->where(array(
'config_key' => 'expiry_duration',
'is_delete' => 0
))->first();
$expiryDuration = $tokenDetail['config_value'];
$expiryTime = date("dmyHis", time() + $expiryDuration);
$created_at = date('Y-m-d H:i:s');
$tokenUpdated = AppToken::updateOrCreate(array(
'user_id' => $user_id,
'token' => $token),
array('expiry'=>$expiryTime,
'created_date'=>$created_at,
'modified_date'=>$created_at)
);
if($tokenUpdated)
{
$return['status'] = 1;
$return['token'] = $token;
}
else
{
$return['status'] = 0;
$return['token'] = $token;
}
return $return;
I am using the updateOrCreate method so that if a record exists, then it will be updated. Else it will be created.
I am getting an exception message,
Add [user_id] to fillable property to allow mass assignment on [App\Http\Model\AppToken].
To be able to use the updateOrCreate method as you did, you have to add user_id to the fillable property within the AppToken class as demonstrated below.
class AppToken extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'user_id', 'token'
];
}
More information on this topic is available here.
You can do it simply by adding this code in your Model file :-
protected $guarded = [];
Like this
class AppToken extends Model
{
protected $guarded = [];
public function fun_name()
{
//function code
}
}
Hope this will help :)
Related
I have done my coding but the laravel audit seems not catch the data for update.
The data i try to update is on the column of value, but on the database the value are not be catch on audit table for auditing the update changes .
below is the coding for update the data.
academicsetting.php:
class AcademicSetting extends Model implements Auditable
{
use SoftDeletes, ActiveScope;
use \OwenIt\Auditing\Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
protected $fillable = [
'id',
'type',
'field',
'name',
'value',
'description',
'is_active',
'created_by',
'created_at',
'updated_by',
'updated_at',
'deleted_by',
'deleted_at',
];
protected $casts = [
'value' => 'json',
];
public function transformAudit(array $data): array
{
dump($data);exit();
if ($data['event'] == 'created') {
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
if ($data['event'] == 'deleted') {
$data['old_values']['deleted_by'] = Staff::where('id', $this->getOriginal('deleted_by'))->value('name');
$data['new_values']['deleted_by'] = Staff::where('id', $this->getAttribute('deleted_by'))->value('name');
}
if ($data['event'] == 'updated') {
$data['old_values']['updated_by'] = Staff::where('id', $this->getOriginal('updated_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
return $data;
}
}
academicgeneralcontroller.php:
public function update(Request $request, $id)
{
/** implode multi dropdown value */
$request['final_attendance_reset_mark'] = $request->input('final_attendance_reset_mark');
/** end */
$this->general->update($request->except('_token', 'academicsetting-table_length', '_method'), $id);
Session::flash('alert-success', msg('msg_success_update'));
return redirect()->route('academic_general.index');
}
generalrepository.php:
class GeneralRepository extends Repository
{
/**
* Specify Model class name
*
* #return mixed
*/
public function model()
{
return AcademicSetting::class;
}
public function update(array $data, $id, $attribute = 'id')
{
// dump($data);exit();
foreach ($data as $key => $value) {
if ($key == 'final_attendance_reset_mark') {
$array = [];
if (!empty($value)) {
foreach ($value as $key_value => $value) {
$array[(int) $key_value] = (int) $value;
}
}
$json = json_encode($array, JSON_FORCE_OBJECT);
// dump($json);
$update_value = [
'value' => $json,
];
} else {
$update_value = ['value' => $value];
}
dump($update_value);exit();
$general = AcademicSetting::where('field', $key)->update($update_value);
}
}
}
Not sure if this will help but,
i see you have the following in the transform method:
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
in the documentation i see the following:
$data['old_values']['role_name'] = Role::find($this->getOriginal('role_id'))->name;
the above is to record the audit by transforming the role_id to the role_name, enabling you to capture the role_name as well.
https://laravel-auditing.herokuapp.com/docs/4.1/audit-transformation
I have a User model which is a parent and Project model which is a child. I created a one-to-many relationship between these two like below.
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function projects(){
return $this->hasMany('App\Project', 'user_id');
}
}
Project Model:
class Project extends Model
{
// Table Name
protected $table = 'projects';
//Primary Key
protected $primaryKey = 'project_id';
// Timestamps
public $timestamps = true;
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
when applying where clause on user model and then getting its related projects:
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::where('email', $request->input('client'))->projects;
}
}
getting error
Exception
Property [projects] does not exist on the Eloquent builder instance.
but when doing
$client = User::find(id)->projects;
above query is giving me results.
Result Expected: i want to get the User model data by WHERE() clause instead of Find() clause and then gets its related projects.
As the Error Says that you dont have property in the Builder
$client = User::where('email', $request->input('client'))->projects;
try this
$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;
here we are getting the user with the specific email and loading the realtion and here you get the relation as object
The source of your issue is that you have not yet retrieved any users. Before calling first() or get() on the query builder, you are limited to functions of the query builder.
Short version: call first() before accessing the projects
$client = User::query()
->where('email', $request->input('client'))
->first()
->projects;
Optional: add with('projects') to eager load the projects. This doesn't add any performance bonus in your case though, as you are only loading a single model.
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::with('projects')->where('id');
}
}
In HomeController this line will retrun collection of array.... In simple words it will return multiple records....
$client = User::where('email', $request->input('client'))->projects;
As you want single record use first (). To retrive single record... It will retrun first matching record...
$client = User::where('email', $request->input('client'))->first()->projects;
I am trying to create REST Api and get this annoying problem. I am using existing table from odoo database which has several records inserted beforehand.
And i realize whenever i want to retrieve the existing row from odoo, the "Carbon Trailing Data" error shows up. But not with the record which i created through laravel eloquent method.
I have already defined the date mutator and cast timestamp mutator to the correct fields of table in the model. But it's still not getting me anywhere. Is there any way other than updating/deleting the date/timestamp value of exsisting records?
Here is some of my codes
Model
namespace App;
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'hr_employee';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
// Private information
'resource_id',
'name',
'user_id',
'active',
'address_home_id',
'country_id',
'gender',
'marital',
'spouse_complete_name',
'spouse_birthday',
'children',
'place_of_birth',
'country_of_birth',
'birthday',
'emergency_contact',
'emergency_phone',
'identification_id',
'passport_id',
'bank_account_id',
'permit_no',
'visa_no',
'visa_expire',
'additional_info',
'km_home_work',
'google_drive_link',
'certificate',
'study_field',
'study_school',
// Work information
'company_id',
'resource_calendar_id',
'department_id',
'job_id',
'job_title',
'work_phone',
'mobile_phone',
'work_email',
'work_location',
'notes',
'parent_id',
'coach_id',
'barcode',
'pin',
'color',
'last_attendance_id',
'create_uid',
'create_date',
'write_uid',
'write_date',
];
const CREATED_AT = 'create_date';
const UPDATED_AT = 'write_date';
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'birthday',
'spouse_birthdate',
'visa_expire',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'create_date' => 'timestamp',
'write_date' => 'timestamp',
];
public function Job() {
return $this->belongsTo('App\Job', 'job_id');
}
public function getNameAcronymAttribute() {
$words = explode(" ", $this->name);
$acronym = "";
foreach ($words as $w) {
$acronym .= $w[0];
}
return $acronym;
}
}
Controller Show Action
public function show($id)
{
$httpCode = 200;
$message = "Here is the employee data";
$modelData = null;
try {
$modelData = Employee::find($id);
if (!$modelData) {
$httpCode = 404;
$message = 'Employee data not found';
}
} catch (Exception $e) {
$httpCode = $e->getCode();
$message = $e->getMessage();
}
return response()->json([
'message' => $message,
'modelData' => $modelData
], $httpCode);
}
When you specify a column in $dates array, laravel converts the values of those columns to Carbon instances. The same happens by default for created_at and updated_at columns.
So all below columns need to be valid timestamp columns :
protected $dates = [
'birthday',
'spouse_birthdate',
'visa_expire',
];
If your columns are not timestamps, you can use casting :
protected $casts = [
'birthday' => 'date:Y-m-d',
'spouse_birthdate' => 'date:Y-m-d'
];
You haven't shown any code.
But from my past experience actually, yesterday had the same problem, first off, use carbon parse to create a carbon instance of the date in order to hook up any other carbon helper methods on the date.
say you have a date like = $date = 2019-02-14
Could now do something like:
$d = Carbon::parse($date);
//hook any further carbon helper methods on the $d variable and it should work
How can I do something such as modify some data fields or more validate before writing data to database in Laravel 5.1 model ?
It's document about that problem is hard to use in real application: http://laravel.com/docs/5.1/eloquent#events
My code is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Helpers\Tools as Tools;
class Atoken extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'atoken';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'token',
'user_id',
'role',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
];
public static function newToken($userId, $role){
# Remove all token assoiciate with input user;
Atoken::where('user_id', $userId)->delete();
$params = [
'user_id' => $userId,
'role' => $role,
];
Atoken::insert($params);
$item = Atoken::where('user_id', $userId)->first();
return $item->token;
}
protected static function boot(){
static::creating(function ($model) {
$model->token = 'sometoken';
});
}
}
In this case, I always got error:
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"token\" violates not-null constraint (SQL: insert into \"atoken\" (\"user_id\", \"role\") values (2, USER))
How can I fix it?
class Lunch extends Eloquent
{
protected static function boot()
{
static::creating(function ($model) {
$model->topping = 'Butter';
return $model->validate();
});
}
protected function validate()
{
// Obviously do real validation here :)
return rand(0, 1) ? true : false;
}
public static function newToken($userId, $role)
{
static::where('user_id', $userId)->delete();
return static::create([
'user_id' => $userId,
'role' => $role,
])->token;
}
}
I would recommend to go into EventServiceProvider, and register event listeners
public function boot(DispatcherContract $events)
{
parent::boot($events);
// Register Event Listeners
\App\Product::updating(function ($product) {
$product->onUpdating();
});
...
then create function onUpdating within the model. You also can choose from saving, saved, creating, created, updating, updated..
This documentation has more:
https://laravel.com/docs/5.1/eloquent#events
hey guys im new in laravel and i was trying to insert into my pivot table. i have this structure in my database
the departments table belongs to many categories and same as category so i have this models
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
protected $fillable = ['department_name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function categories()
{
return $this->belongsToMany('Categories');
}
}
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Categories extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function department()
{
return $this->belongsToMany('Departments');
}
}
then i have a query in my controller like this
$messages = array(
'required' => 'Please Fill the required field',
'unique' => 'Name Already exist'
);
$catName = Input::get('categoryName');
$deptId = Input::get('deptId');
$validation = Validator::make(Input::all(),[
'categoryName' => 'required|unique:categories,name' ], $messages);
if($validation->fails()){
return array('error' =>$validation->messages()->all() );
}else{
$findDepartment = Departments::find($deptId);
$saveCat = $findDepartment->categories()->insert(array('name' => $catName));
}
but then when i checked the tables it adds up on the categories table but nothing is added in the category_department. do i miss any codes? and also i had an error last time I was trying to migrate my pivot table the error was this.
can you help me guys on what i am missing? tnx for the help in advanced.
First, you should name your model classes as singular: Category, Department.
Then try to declare your relationships with the pivot table name:
public function categories()
{
return $this->belongsToMany('Category', 'category_department');
}
and
public function departments()
{
return $this->belongsToMany('Departments', 'category_department');
}
now, to insert new data, try attach:
$findDepartment = Department::find($deptId);
$category = Category::where('name', '=', $catName)->first();
$saveCat = $findDepartment->categories()->attach($category->id);