Laravel 5.4 default value in role_id - laravel-5.4

in fact I am new to laravel, and I have a problem with my application.
I have a table USERS (id, login, password, role_id, firstname, lastname, email)
I would like to record and the role_id always has a default value of 1, because at my place in ROLES table (id, role) the admin has ID 1 and the member has the value 2.
I would like that the modification is in the controller or model not on the migrations.
thank you in advance

When you saved user and you have data add role_id key in data.
Fore example
Controller
public function (Request $request) {
$data = $request->all();
$data['role_id'] = 1;
if (User::create($data)) {
// some message for successfully created
return redirect('some-route');
}
// some message for failed to save user
return redirect()->back();
}

Related

Eloquent retrieve data from another model on runtime

I have two tables;
Data
id
name
Custom_data
id
data_id (references id on Data)
customer_id (references id on Customers)
name
When I retrieve all items from the database (via for example Data::all()) as Customer X then I want to retrieve values from 'Custom_data' in favor of the data in table 'Data' where the customer_id matches X
Example:
Data contains name 'John Doe' with id 1
Custom_data contains a record with data_id 1 and name 'Jane Doe' and customer_id X
When retrieving the models I want to see Jane Doe instead of John Doe. Can this be done on a Model level in Eloquent? This is just a simple example, in our application we have multiple columns that need to be retrieved (firstname, lastname, street, etc. etc.)
How I am currently retrieving the fields is like this:
public function getNameAttribute($name) {
$customData = CustomData::where('customer_id', $this->customer_id)->where('data_id', $this->id)->first();
if(null != $customData) {
return $customData->name;
} else {
return $name;
}
}
Here' how you can do it:
In your Data.php modal file you need to add relationship:
public function CustomData(){
return $this->hasOne(CustomData::class);
}
Now, you can use CustomData function on eloquent record anywhere in Controller or View at runtime to get related data.
Another approach is to get data on condition basis:
$users = User::select('users.id', 'users.username', 'users.active', 'users.parent_id', 'parent.username as parent_username')
->selectRaw("CASE WHEN GROUP_CONCAT(roles.name) = 'student' THEN user_profiles.secondary_email ELSE users.email END as email");
I've used this type of solution for another purpose where I needed to use email on condition basis.
first you need to define relation in model
class DataModel extends Model{
...
public function customData()
{
return $this->hasMany(CustomDataModel::class,"data_id");
}
}
now you have access to this data.
$data = DataModel::with("customData")->first();
$data->name; // John Doe
$data->customData->name; // Jane Doe
Allright, I think I nailed this one.
I made a hasOne relation in my Data model:
public function custom_data() {
return $this->hasOne('App\Models\CustomData', 'data_id')->where('customer_id', $customer_id);
}
After that, I could fairly easily add the correct accessors like so:
public function getNameAttribute($name) {
return null != $this->custom_data ? $this->custom_data->name : $name;
}
If the custom data attribute has been set, we'll return that. If not, we'll return the original attribute.

Laravel: hasMany relationship + where condition fails

I have a Customer Eloquent model. Customer can have multiple WishLists where he / she can add some products. Typical ecommerce functionality.
The point is that Customer can belong to many Users models.
This was easy:
public function users()
{
return $this->belongsToMany(User::class, 'users_sync_customers', 'customer_uuid', 'user_id')
->withTimestamps()
->orderBy('last_name', 'asc');
}
So I can get all Customers assigned for logged in user by
auth()->user()->customers 🎉
As I mentioned, Customer can have multiple Wishlists:
public function wishLists()
{
return $this
->hasMany(WishList::class, 'customer_uuid', 'uuid')
->where('user_id', '=', auth()->user()->id); // <----- this will fail when I log out
}
but WishList is scoped to both Customer UUID and User ID.
Above relationship works but only when I'm logged in obviously.
As soon as I log out the auth()->user()->is is NULL and I get:
ErrorException {#1483 #message: "Trying to get property 'id' of
non-object"
Question: How can I reference in wishLists() the user_id value?
WishList model has this:
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
So can I use something like $this->user->id?
edit:
Nope, this also doesn't work.
you must check that the user is logged in?
Auth::check() ? Auth::user()->id : null

Laravel getting data of logged in user from different tables based on foreign keys and id

Hi iam beginner of laravel ,i have four tables users,students,class,section
users
id
username
password
usertype
Students
id
name
roll no
class_id
section_id
class
id
class_name
sections
id
section_name
when i logged in getting user name and getting role no from student tables by using following method
User.php
public function getAttribute($key)
{$profile = student::where('stud_adm_id', '=', $this->attributes['username'])->first()->toArray();
foreach ($profile as $attr => $value) {
if (!array_key_exists($attr, $this->attributes)) {
$this->attributes[$attr] = $value;
}
}
return parent::getAttribute($key);
}
But i want to get class name and section name from related tables also to show logged in user complete profile....
and in view page called values as shown below
<h4>ID: {{ Auth::user()->roll_no}}</h4>
<h4>Name: {{ Auth::user()->name }}</h4>
Let me know how to get values of class and section also.
You can use Eloquent: Relationships.
Defining relationships in student.php
class Student {
...
public function class() {
$this->belongsTo('App\Class');
}
public function section() {
$this->belongsTo('App\Section');
}
...
}
Then you can retrieve the class and section relationship when you get the student model.
$student = Student::where('stud_adm_id', $username)->first();
$class = $studnet->class;
$section = $student->section;

Laravel Request ip address for login users

i made login_history table with fields user_id foreign for users table , ip_address and created_at i need to very time to login user save it in login_history table now i'm using
Listeners or last_login users using laravel 5.2 with this code
public function handle(Login $event)
{
$user = \Auth::user();
$data = new LoginHistory();
$event->user->$data->user_id = $user->id;
$event->user->$data->created_at = Carbon::now();
$event->user->$data->ip_address = Request::getClientIp();
$event->user->$data->save();
}
**but this not i want
please any one can help for changing this code i have model created
class LoginHistory extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
and i get this error
Cannot use Illuminate\Foundation\Auth\User as User because the name is
already in use
thanks
Considering you have a Model for the LoginHistory pivot table. In any controller method, you can use the following code.
$user = auth()->user();
LoginHistory::create(['user_id'=>$user->id,'ip_address' => Request::getClientIp(), 'created_at'=>Carbon::now()]);
And if you don't have the model, you can use the DB facade to do the same.
You can create a Middleware in laravel in handle method you can insert the data
$event->user->$data->ip_address = \Request::ip(),

yii2 multi step form

I have just got accustomed to yii2
Am creating a multistep form in yii2 which involves three related tables
tables
User table:has (idno(primary key), firstname, secondname and lastname)
Education table has: (idno(foreign key), institution_name, year_completed, grade)
Contacts table has: (idno(f.key),contact)
Models and relationships
Relation btwn user and contacts
public function getContacs()
{
return $this->hasMany(Contacts::className(), ['idno' => 'idno']);
}
public function getUser()
{
return $this->hasOne(User::className(), ['idno' => 'idno']);
}
Relationship btwn user and education
public function getEducation()
{
return $this->hasMany(Education::className(), ['idno' => 'idno']);
}
public function getUser()
{
return $this->hasOne(User::className(), ['idno' => 'idno']);
}
How can I create a multistep form that is in the first step a user fills in the his details on the next step on education details the form automatically picks the userid and passes it to the education details until finishing
you need to maintain a flag for each step , for example for first_step = 0 , second_step = 0 third_step = 0 . if first step is filled out change the first_step = 1 do same for other , this fields should be present in user table or you can maintain another table using user id as foreign key . if first_step = 1 then when you login again and page will open where flag = 0 mean it will open the second step directly. This is a basic concept so you can get idea , There are other ways also .