Laravel Eloquent ORM inserts - php

is there a shorter way to insert data in Laravel over the Eloquent ORM?
at the moment i'm doing it this way:
$newCustomerGsale = new CustomersGsale();
$newCustomerGsale->email = $gsalesCustomer->getEmail();
$newCustomerGsale->customerno = $gsalesCustomer->getCustomerNumber();
$newCustomerGsale->created = $gsalesCustomer->getCreated();
$newCustomerGsale->company = $gsalesCustomer->getCompany();
$newCustomerGsale->firstname = $gsalesCustomer->getFirstname();
$newCustomerGsale->lastname = $gsalesCustomer->getLastname();
$newCustomerGsale->save();
like you see all the columns are named like the attributes.
I know u can use the $request object with all() function and fetch().
but I get the data from a other object (soap server).
is there a way to convert this? maybe over the model?

Your controller
Assume CustomersGsale is your model
public function store(CustomersGsaleFormRequest $request)
{
CustomersGsale::create($request->all());
}
CustomersGsaleFormRequest.php Laravel Form Requests Validation
public function rules()
{
return [
'email' => 'required|email',
'customerno' => 'required',
'created' => 'required',
'company' => 'required',
'firstname' => 'required'
];
}
CustomersGsale.php Model
your attributes and columns should be the same.
If you are using the create method for store the data then you will need to specify either a fillable or guarded attribute on the model
class CustomersGsale extends Model
{
protected $fillable = [
'email', 'customerno', 'created', 'company', 'firstname', 'lastname'
];
}

//MyControllerClass
public function store(myCustomValidator $request){
CustomersGsale::insert($request->all());
}
//myCustomValidator class
public function rules(): array
{
return [
'email' => 'required|numeric',
'customerno' => 'required',
'created' => 'required',
'company' => 'required',
'firstname' => 'required'
'lastname' => 'nullable'
];
}
Try the above method, hope this will work for you.

Related

How to fetch and store data from other table to user table. Laravel 8

Form
{!! Form::select('grade_level[]', $grade_level,[], array('class' => 'form-control','multiple')) !!}
Controller
Here is my create function that will return the a view and the list of roles and grade level for users
public function create()
{
$grade_level = GradeLevel::pluck('grade_level','id')->all();
$roles = Role::pluck('name','name')->all();
return view('users.create',compact('roles','grade_level'));
}
Here is the store function. and I have encounter a problem MySql Error: 1364 Field 'grade_level_id' doesn't have default value
public function store(Request $request)
{
$this->validate($request, [
'f_name' => 'required',
'm_name' => 'required',
'l_name' => 'required',
'sex' => 'required',
'id_number' => 'required',
'address' => 'required',
// 'email' => 'required|email|unique:users,email',
'username' => 'required|unique:users',
'password' => 'required|same:confirm-password',
'grade_level_id' => 'required',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->grade_level_id = $request->grade_level;
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
I see you're using User::create() method to add new user, you'd need to add grade_level_id to the fillable property or your User model.
protected $fillable = [
'grade_level_id'
];
Find More about it here : https://laravel.com/docs/8.x/eloquent#mass-assignment
Either add 'grade_level_id' to the $fillable of your user model,
or
inside your migration, you can add the ->nullable(); extension to the grade_level_id field declaration

Laravel, How to ignore (except) some fields when update model using json and laravel

The function below is to update user information, I need to validate if email is not duplicated, also to ignore password if its field left empty, I don't why this function not working!
public function update(Request $request, $id)
{
$this->validate($request->all(), [
'fname' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all()->except(['country_id', 'region_id']);
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return response()->json(array('data' => trans('message.success')));
}
Firstly, you need to correct your validation.
You need to change it to
$request->validate([
'fname' => 'required',
'email' => [
'required',
'email',
Rule::unique('users')->ignore($id),
],
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$request->all() returns an array, you need to change it to
$input = $request->except(['country_id', 'region_id']);
Also I would change the condition to use Laravel's build-in method:
if($request->filled('password'))
Pass the $request object not $request->all(), that returns an array of the input.
$this->validate($request, [
'fname' => 'required',
'email' => [
'required',
Rule::unique('users')->ignore($id),
],
'password' => 'nullable,confirmed',
'roles' => 'required'
]);
I changed the password rule to check if it exists and if it does, it confirms it matches.
Again, I removed the chained all() method
$input = $request->except(['country_id', 'region_id']);
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
Remember to use
use Illuminate\Validation\Rule;

Laravel 5 Update Validation email needs to be unique

I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40

How to use eloquent-relationships on laravel 5.3?

My controller is like this :
public function create()
{
$data = array(
'email' => 'chelsea#gmail.com'
);
$data = Order::where('email', $data['email'])->first();
dd($data);
}
My model order is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
class Order extends Model
{
use SoftDeletes, Notifiable;
public $table = 'orders';
protected $dates = ['deleted_at'];
public $fillable = [
'number',
'user_id',
'store_id',
'total_amount',
'total_product',
'service_amount',
'status',
'checkout_at'
];
protected $casts = [
'number' => 'string',
'user_id' => 'integer',
'store_id' => 'integer',
'total_amount' => 'integer',
'total_product' => 'integer',
'service_amount' => 'integer',
'status' => 'integer',
'checkout_at' => 'date'
];
public static $rules = [
'user_id' => 'required',
'store_id' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}
}
table user have field id, name, email etc
table store have field id, name, email etc
I want get user name and store name from table user and table store. Then, I want store it on variable $data
How can I do it?
UPDATE
My model user is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
public $table = 'users';
protected $dates = ['deleted_at'];
public $fillable = [
'name',
'email',
'password',
'full_name',
'birth_date',,
'mobile_number',
];
protected $casts = [
'name' => 'string',
'email' => 'string',
'password' => 'string',
'full_name' => 'string',
'birth_date' => 'date',,
'mobile_number' => 'string',
];
public static $rules = [
'name' => 'required',
'email' => 'required'
];
}
My model store is like this :
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Store extends Model
{
use SoftDeletes;
public $table = 'stores';
protected $dates = ['deleted_at'];
public $fillable = [
'user_id',
'domain',
'name',
'email'
];
protected $casts = [
'user_id' => 'integer',
'domain' => 'string',
'name' => 'string',
'email' => 'string'
];
public static $rules = [
'user_id' => 'required',
'domain' => 'required',
'name' => 'required'
];
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
}
First you need to make model for User Table and Store table then define respective table names in both model after that......
public function create(Request $request)
{
$data = $request->all();
$email = 'chelsea#gmail.com';
$user = User::where('email', $email)->first();
$store = Store::where('email', $user->email)->first();
$order = Order::where('user_id', $user->id)->where('store_id', $store->id)->first();
$result = array();
$result['orderTable'] = $order;
return $result;
}
Use with in your order controller query, just pass the array of relationships that you have declared in your order model query will fetch the related tables data based on model relations, like below
In order controller
$data = Order::where('col', 'val')->with(['user','store'])->first();
In order model
public function user()
{
return $this->belongsTo(User::class,'user_id','id');
}
public function store()
{
return $this->belongsTo(Store::class,'store_id','id');
}

Call to undefined method Query\Builder

I have a protected function that I want to use to check my login validation. However I am getting the error
Call to undefined method Illuminate\Database\Query\Builder::loginValidation
Do I have to write a model for my function?
Login Validation:
protected function loginValidation($data)
{
$rules = array(
'fname' => 'required|max:255',
'lname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
);
return Validator::make($data, $rules);
}
getLoginCredentials
protected function getLoginCredentials(Request $request)
{
$validator = User::loginValidation(Request::all());
if($validator->passes())
{
return[
'email' => Request::input('email'),
'password' => Request::input('password'),
'type' => 1
];
return true;
}else{
return redirect()->back()->withErrors();
}
}
I guess the user model can not see your function. Do composer dump-autoload to see if the changes will reflect. if it does not try a new name and see if it will work.

Categories