I want to get the logged in user id and insert it into the Salesprice table,I have tried the below code but it gives me the this error
"SQLSTATE[HY000]: General error: 1364 Field 'setby_id' doesn't have a
default value (SQL: insert into salesprices (book_id,
salesprice, remarks, updated_at, created_at) values (2, 5566,
?, 2020-01-31 03:59:58, 2020-01-31 03:59:58))"
code in controller is
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Salesprice;
use Illuminate\Support\Facades\Hash;
use App\User;
use Illuminate\Support\Facades\Auth;
public function store(Request $request)
{
try
{
$user = auth('api')->user();
$this->validate($request,[
'book_id'=>'required',
'salesprice'=>'required',
]);
$Salesprice= Salesprice::create([
'book_id'=>$request['book_id'],
'salesprice'=>$request['salesprice'],
// 'setdate'=>$request['setdate'],
'setby'=> $user->id,
'lastmodifiedby'=>$user->id,
'remarks'=>$request['remarks']
]);
return response()->json($Salesprice);
}
catch (Exception $e)
{
return response()->json($e->getMessage(), 500);
}
}
code in migration and model is
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Salesprice extends Model
{
//
use SoftDeletes;
protected $fillable = [
'book_id','salesprice','setby_id','modifiedby_id','remarks'
];
public function Book()
{
return $this->hasOne('App\Book');
}
public function User()
{
return $this->hasOne('App\User');
}
protected $dates=['deleted_at'];
}
public function up()
{
Schema::create('salesprices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('book_id')->unsigned();
$table->bigInteger('salesprice');
$table->bigInteger('setby_id')->unsigned();
$table->bigInteger('modifiedby_id')->unsigned();
$table->string('remarks')->nullable();
$table->softDeletes();
$table->timestamps();
});
}
auth()->user()is correct
The only thing you have to do is to change your
setby to setby_id Becaseu you're doing:
'setby'=> $user->id,
but your column is named setby_id, so you need:
'setby_id'=> $user->id,
Because this field cannot be nullable.
So when you insert the value without setby_id, it will fail.
Change setby to setby_id
$Salesprice= Salesprice::create([
...
'setby_id'=> $user->id, // change to setby_id
...
]);
Nothing's wrong with auth()->user().
You're doing:
'setby'=> $user->id,
but your column is named setby_id, so you need:
'setby_id'=> $user->id,
You'll have the same issue with lastmodifiedby versus modifiedby_id.
Related
according to this thread Yii2 - left join on multiple condition
i create sql function in Mfwpcontroller like this :
use Yii;
use app\models\Mfwp;
use app\models\User;
use app\models\MfwpSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
public function actionLists($id)
{
$posts = Mfwp::find()
->joinWith(['user' => function (ActiveQuery $query) {
return $query
->andOnCondition(['=', 'user.id', 'mfwp.id_mfwp'])
->andWhere(['=', 'mfwp.id', $id]);
}])
->asArray()
->all();
Yii::$app->response->format = 'json';
return $posts;
}
and this is my model in mfwp
public function getMfwp()
{
return $this->hasOne(User::className(), ['id' => 'id_mfwp']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSmWps()
{
return $this->hasMany(SmWp::className(), ['id_sm_wp' => 'id']);
}
when i try to execute by accessing http://bla-bla.oke/mfwp/lists?id=1, its show an error
Invalid Argument – yii\base\InvalidArgumentException
app\models\Mfwp has no relation named "user".
↵
Caused by: Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\models\Mfwp::getuser()
and this is my database structure https://imge.to/i/vE2nWC
so whats wrong with my code..thank you for your advice
4 and i have a form when submitted i want to validate its fields, what happened is when i submit the form this is what it gets
(1/1) FatalErrorException
Call to a member function all() on null
This is my code below
$validator = app('validator')->make($this->request->all(),[
'postTitle' => 'required',
'postContent' =>'required']);
In laravel 5.2 this validator works well but in laravel 5.4 it returns null
can someone help me figured this thing out?
Any help is muchly appreciated. TIA
this is my full code
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use Illuminate\Http\Request;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
protected $request;
// Intialize request instance
public function __contruct(Request $request){
$this->request = $request;
}
public function addPosts(Request $request){
//validate posts
echo "test";
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
}
Seems an issue with the method injection (in the constructor) or something.
You may try creating the request object on the local(addPosts()) function.
Please try below alternative solution.
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
public function addPosts(Request $request){
//validate posts
$reqeust = new \Illuminate\Http\Request;
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
// REST OF THE CODE GOES HERE...
}
Given the information you gave, I will demonstrate you how to validate a request properly in Laravel 5.4
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
if ($validator->fails()) {
return redirect('your.view')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
This will successfully validate the request for you wherever need be. If the validation fails, you will be forwarded to your view with the according errors.
Make sure you use Validator; on top of your file.
For more information, you can read up on https://laravel.com/docs/5.4/validation
I have 3 models. User, Notification and Lmo Notifications. The relation is a User hasMany Notifications and Notification has many LmoNotification.
to insert the notification and lmoNotification i created two models and controllers and they have separate database tables.
My problem is when i enter notifications into the database, it inserts data without any problem with user_id as the foreign key. But next when i try to enter the lmonotification, it gives an error.
Notification Model:
class Notification extends Model
{
protected $table = "notifications";
protected $fillable = [
'unit_code', 'unit_name', 'project_title', 'project_ref_number', 'storage_location', 'keeper_name', 'user_id',
];
public function user(){
return $this->belongsTo('App\User');
}
}
LmoNotification Model
class AddLmoNotification extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = "lmo_notifications";
protected $fillable = [
'lmo_name', 'lmo_risk_level', 'lmo_quantity', 'lmo_volume', 'notification_id',
];
public function notification(){
return $this->belongsTo('App\Notification');
}
}
Notification controller to create the notification
public function create(Request $request)
{
$notification = Notification::create([
'unit_code'=>$request->unit_code,
'unit_name'=>$request->unit_name,
'project_title'=>$request->project_title,
'project_ref_number'=>$request->project_ref_number,
'storage_location'=>$request->storage_location,
'keeper_name'=>$request->keeper_name,
'user_id'=>Auth::user()->id
]);
return redirect()-> route('show.lmo_form', $notification->id);
// return view('ApplicationForms.notifi', $notification);
}
Lmonotification controller
$notification = new Notification;
/*this loop is because im adding rows dynamically to the table*/
$count = count($request->input('lmo_name'));
for ($i=0; $i<$count; $i++){
$data = AddLmoNotification::create([
'lmo_name'=>$request->lmo_name[$i],
'lmo_risk_level'=>$request->lmo_risk_level[$i],
'lmo_quantity'=>$request->lmo_quantity[$i],
'lmo_volume'=>$request->lmo_volume[$i],
'notification_id'=>$notification->id
]);
return response($data);
}
//return response($notification);
return redirect()->route('show.go_to_notification');
}
web.php
Route::prefix('notification')->group(function(){
/*show notification main page*/
Route::get('/', 'HomeController#getNotificationPage')->name('show.go_to_notification');
/*route to lmo_notification_form*/
Route::get('/personal_information_notification_form', 'HomeController#getNotificationForm');
/*route to biohazardous material notification form*/
Route::get('/biohazardous_material_notification_form', 'HomeController#getotherNotificationForm')->name('show.biohazardous_material_notification_form');
/*submit lmo notification route*/
Route::post('/personal_information_notification_form/submit', 'NotificationController#create')->name('submit.personal_Info_Notification');
/*Rtoute to lmo form*/
Route::get('/personal_information_notification_form/add_lmo/{notification_id}', 'HomeController#getlmoNotificationForm')->name('show.lmo_form');
/*Route to submit lmo list for notification*/
Route::post('/personal_information_notification_form/add_lmo', 'LmoNotificationController#create')->name('submit.lmo_list');
});
Notification table
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('unit_code')->nullable();
$table->string('unit_name')->nullable();
$table->string('project_title')->nullable();
$table->string('project_ref_number')->nullable();
$table->string('storage_location');
$table->string('keeper_name');
$table->timestamps();
});
Lmo Notification table
public function up()
{
Schema::create('lmo_notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('notification_id')->unsigned();
$table->foreign('notification_id')->references('id')->on('notifications')->onDelete('cascade')->onUpdate('cascade');
$table->string('lmo_name');
$table->string('lmo_risk_level');
$table->string('lmo_quantity');
$table->string('lmo_volume');
$table->timestamps();
});
}
the notification table contains some personal details fields and the lmonotification contains list of products.
the error message says that
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'notification_id' cannot be null (SQL: insert into lmo_notifications (lmo_name, lmo_risk_level, lmo_quantity, lmo_volume, notification_id, updated_at, created_at) values (asd, medium, 2, 2, , 2017-05-09 22:35:15, 2017-05-09 22:35:15))
Please help.
There is nothing wrong with your relations setup. The problem starts where you set the notification_id of your new AddLmoNotification off of a model you instantiated with:
$notification = new Notification;
Note that as long as $notification is not persisted to database with:
$notification->save()
that notification will not have an ID assigned to it by the database, and thus, accessing its id attribute returns null. So you'll have to save the $notification model first, before creating any models that rely on its id attribute for their foreign-key fields.
I have a Model called User and another Model called Roles and they are linked with each other through a belongsToMany relationship. But I needed to cast certain pivot attributes so I used a custom pivot class RoleUserPivot which basically looks like follows:
...
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleUserPivot extends Pivot
{
protected $casts = [
'active' => 'boolean',
'permissions' => 'array',
];
}
...
The relationship definition in User and Role models is as follows:
...
// User Model
public function roles()
{
return $this
->belongsToMany('App\Role')
->withPivot(
'active',
'permissions'
);
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Role) {
return new RoleUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
...
And similarly:
...
// Role Model
public function users()
{
return $this
->belongsToMany('App\User')
->withPivot(
'active',
'permissions'
);
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof User) {
return new RoleUserPivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
...
The problem I am having is, while the active field is properly cast to boolean, the permissions field is not cast to array, instead the same string in the database is returned. I assure that the pivot table is properly setup and permissions column is MySQL TEXT column.
Currently I am using Laravel 5.1.16 (LTS).
I want to pull the model data with custom attribute that assigned in a function in model.
Example)
class Test extends ActiveRecord
{
public static function tableName()
{
return '{{%test}}';
}
public function rules()
{
//....
}
public function attributeLabels()
{
return [
'id' => 'ID',
'first_name' => 'First Name',
'last_name' => 'Last Name',
];
}
public function getFullName()
{
$fullName = $this->first_name.' '.$this->last_name;
return $fullName;
}
}
Test::find().with('fullName') => it doesn't work
How can I get all the data with fullname attribute?
with is for relations. You can get fullname attribute just by calling $model->fullName. Actually fullName is not an attribute, yii2 utilise php's magic method __get() to get it from getFullName() method.
Example:
$model = Test::findOne($id);
echo $model->fullName;
Example 2:
$models = Test::find()->all();
foreach($models as $model)
{
echo $model->fullName;
}
Also consider using of fields/extraFields methods if you want use your models as arrays instead of objects