Inputing values into a database with Laravel 5.3 - php

I can't for the life of me find info on how to do this despite my gut telling me its a basic fundamental.
I have a simple boolean that redirects users based on a table value reference_id. I want it to redirect the user after inputting a value in a column in that user's row.
Here is the code: (you can ignore the code I commeneted out. That's for a different implementation)
https://gyazo.com/9f2774cd9069b4678d67b80391f9f276
protected function redirectTo()
{
$id = Auth::id();
$rfid = DB::table('users')->where('id', $id)->value('reference_id');
//$userid = User::find($id);
if ($rfid == ''){
//$clientRole = DB::table('roles')->where('id', '2')->value('slug');
//$userid->attachRole($clientRole); // sets role based on redirect
input 'client' to database 'users' column 'temproles' //dummy code for what I want to do
view('/clientdirect');
}
else {
//$employeeRole = DB::table('roles')->where('id', '3')->value('slug');
//$userid->attachRole($employeeRole); // sets role based on redirect
input 'employee' to database 'users' column 'temproles'
view('/empdirect');
}
}
Again my apologies if this is common knowledge, I couldn't find a reference source anywhere. Either a link to where I can read about this or directions would be great!

If you want to input 'client' on a table called 'users' in a column 'temproles' you should be able to accomplish that by this:
DB::table('users')->insert(
['temprole' => 'client']
);
If you have models created you could do the following:
$user = new User
$user->temproles = 'client';
$user->save();

Related

Updating DB tables based on relationships Laravel 5.8 and Eloquent

I have a problem with updating tables that belongTo another table.
I have a users table and a recipes table. The Recipe model belongsTo the User model and the User model hasMany Recipe.
Each recipe is shown in my index view as a small card and on that card, as well as on each individual show page, I am printing recipe->author. When a recipe is created, it takes the username attribute from the users table and sets this as the author attribute on the recipes table. However, when I update the username of a user, the author attribute in the recipes table does not update accordingly.
User Model
public function recipes(){
return $this->hasMany('App\Recipe');
}
Recipe Model
public function user(){
return $this->belongsTo('App\User');
}
Can I possible add some logic in my UserController to account for this when I update a user?
UserController#update
$user = Auth::user();
$this->validate(request(), [
'name' => 'required',
'username' => 'required',
]);
// Handle File Upload
if(request()->hasfile('profile_pic')){
// Get filename with extension
$fileameWithExt = request()->file('profile_pic')->getClientOriginalName();
// Get just filename
$filename = pathinfo($fileameWithExt, PATHINFO_FILENAME);
// Get just extension
$extension = request()->file('profile_pic')->getClientOriginalExtension();
// Filename to store
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
// Upload Image
$path = request()->file('profile_pic')->storeAs('public/profile_pictures', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
$user->name = request('name');
$user->username = request('username');
$user->description = request('description');
$user->location = request('location');
if(request()->hasFile('profile_pic')){
$user->profile_pic = $fileNameToStore;
}
$user->push();
$user_id = Auth::user()->id;
return redirect()->route('user', ['id' => $user_id]);
}
I have read the Laravel docs and can't find anything that will quite do what I am looking for. Would appreciate any guidance!
You mean you store username in users, and you want to store the exact username in the author of recipes?
Why not you just reference the name using relationship $recipe->user->username. It would query your users table based on your user_id in your recipes and get that username for you.
So that you're not storing duplicating data in your database. There should be only one Single Source of Truth. You can get your user data based on your user_id, there's no point to store another set of data and keep updating it when the source is changed.
If you find querying whole User model a bit of heavy, then you can use Recipe::with('users:id,username')->get() to query only the username.
Or
If you want to maintain the current $recipe->author, you can:
// Recipe class
public function getAuthorAttribute() {
return $this->user->username;
}
If you set up the foreign keys on your migration files, you may add the ->onUpdate('CASCADE') clause to the username foreign on the recipes table migration.
Note: the onCascade foreign constraint would work outside of Laravel too, as it relies only on the database engine's support for foreign keys.
Anyways, be careful with your validation as you have to be sure the new chosen username isn't already used by someone else.
Assuming your User model is connected to the users table and has an id primary key, make sure that you set the username column as unique in the database, and **validate* user input accordingly.
The former is done by editing once again your migration.
The latter is solved by modifying your rules like these ones:
// Do not forget the Rule import at the top of your controller
use Illuminate\Validation\Rule;
// Then in your method
$this->validate(request(), [
'name' => 'required',
'username' => [
'required',
Rule::unique('users', 'username')->ignore($user)
]
]);
Note: if you modify migrations you have to rerun them in order to apply the modification.

How to joins table in Laravel 5.2?

I am beginner in Laravel Framework.I have searched for my problem and get some solution but those are not solve my problem.So,
profiles table:
I want to need to fill up userID column when any user create a profiles.For this i am trying to code something like this:
Profile model:
public function users(){
return $this->belongsTo('App\User','userID');
}
And User Model:
public function profiles()
{
return $this->hasMany('App\Profile');
}
In this way its keep null value every time.How can i solve this?
Thanks in advanced.
So assuming you have the following (which you kind of do)
public function profiles()
{
return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}
<?php
// Profile.php (Model)
public function user()
{
$this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}
You have a few options, you can either when creating the profile, assign the user_id (as long as it is in the fillable fields.
$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();
Or since we have a relationship you should be able to do something like this
$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.
Hopefully that sheds some light
While inserting Data into Profile Table, you just need to do as follows:
$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();
There is no need to join the tables for inserting the value in Profile Table for here. Hope this helps you

Laravel 5 - Set Model and Table during Runtime Not Working

I am doing two different types of auth for 'student' and 'consultant', thus two tables.
So far everything works fine. A user can choose usertype and then login, but when I'm printing {{ Auth::user()['username'] }} in the page error occurs: only 'student' name can be displayed, since I specified model and table in config/auth.php to be 'Student' and 'students'. As for consultant users, they can successfully login, but username can't be displayed.
I tried to set model and table with config during runtime but doesn't work, here's part of my AuthController:
if( $request->only('usertype')['usertype'] == 'student' ) {
Config::set('auth.model','Student');
Config::set('auth.table','students');
$userprovider = new \Illuminate\Auth\EloquentUserProvider(app('hash'), 'App\Student');
Auth::setProvider($userprovider);
$this->redirectPath = '/student/home';
}
else if( $request->only('usertype')['usertype'] == 'consultant' ) {
Config::set('auth.model','Consultant');
Config::set('auth.table','consultants');
$userprovider = new \Illuminate\Auth\EloquentUserProvider(app('hash'), 'App\Consultant');
Auth::setProvider($userprovider);
$this->redirectPath = '/consultant/home';
} $credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
Seems the Config::set doesn't work at all. What could be the problem?
I'm using Laravel 5.1.
Let me try answering my question, based on jedrzej's solution in the comment.
Config::set did work, but only for once and needs to be modified for every request for authentication. In this case, doing a middleware is an ideal solution - store user type in session on successful login and then in the middleware read that value from session and set config variables - laravel.com/docs/master/middleware.
Another easier solution is using some package for multi-auth. I used Sarav\Multiauth (https://packagist.org/packages/sarav/laravel-multiauth) and it works perfectly.

updating related tables from a controller laravel

Hi I’ve a users and education table. A user can have multiple school or college. So its one to many relationship. education table has school, from_year, to_year and user_id (fk) I want to update the user table as well as education table from a PUT request to users/{id} with email,school, from_year, and to_year fields.
// UsersController.php
public function update(Request $request, $id)
{
$user = User::find($id);
if (!$user) {
return $this->respondNotFound('User not found');
}
$input = $request->all();
$input = array_filter($input, 'strlen');
//$user->update($input);
//Get array of school records
// $user->educatoion->push($records) // don't know what will come here to update the education table
// or may be $user->push(); // don't know
return $this->respond([
'data' => $user,
]);
}
Try to keep it as simple as possible.
If this is your first time updating multiple tables at once, draw up a diagram of the process. This way you can identify the correct order of updates.
Take care to note any formatting that has to done on each value.
Laravel has some great functionality in regards to binding input to a model using ->update($data)
However, when binding to multiple models, you might run into issues with duplicate field names.
Update:
To create a education row from the $user model:
$education = new Education(array('school' => 'Harward', 'from_year' => 1999, 'to_year' => 2016));
User::find($id)->education()->save($education);

Dynamically populating the dropdown menus in PHP Cake. Access Model from another Model?

I am building a Cake PHP application. Different users have different properties so I use two objects to store a user for example
User hasOne Student / Student belongs to User
User hasOne Lecturer / Lecturer belongs to User
The profile edit page will allow the User to edit all their details for both objects. I've set up the form and used saveAll so save both objects. My problem is dynamically populating the dropdown menus depending on which role the user has.
For example the counties field. Admin does not have an address whereas Student and Lecturer do. I have setup my Country model to find all my counties and put them into opt-groups in the select box (sorting them by country as shown here Dropdown list with dyanmic optgroup)
I can do this fine inside the Students/LecturersController as they allow me to access the Country model as I set $uses variable. I do not want to do this inside the UsersController as not all user roles have an address and an address is never stored inside the User object. I tried putting the code in the model but then I don't know how to access other Models inside a Model. Up to now I've had no problem building the app and I feel that I may have made a bad design decision somewhere or there's something I'm not understanding properly.
Essentially I'm asking how do I implement the setForForm() function below.
public function edit() {
//get user
$user = $this->Auth->user();
//get role
$role = $user['User']['role'];
if ($this->request->is('post') || $this->request->is('put')) {
//get IDs
$userID = $user['User']['id'];
$roleID = $user[$role]['id'];
//set IDs
$this->request->data[$role]['user_id'] = $userID;
$this->request->data[$role]['id'] = $roleID;
$this->request->data['User']['id'] = $userID;
//delete data for role that is not theirs
foreach ($this->request->data as $key => $value) {
if($key !== 'User' && $key !== $role) {
unset($this->request->data[$key]);
}
}
if ($this->User->saveAll($this->request->data)) {
//update logged in user
$this->Auth->login($this->User->$role->findByUserId($userID));
$this->Session->setFlash('Changes saved successfully.');
} else {
$this->Session->setFlash(__('Please try again.'));
}
}
//set role for easy access
$this->set(compact('role'));
//sets required variables for role form
$this->User->$role->setForForm();
//fills in form on first request
if (!$this->request->data) {
$this->request->data = $user;
}
//render form depending on role
$this->render(strtolower('edit_' . $role));
}
//this is the method I would like to implement in the Student/Lecturer model somehow
public function setForForm() {
$counties = $this->Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
Not sure if I get your question correct, but I think what you want is the following:
User hasOne Student / Student belongs to User
and
Student hasOne Country / Country belongsTo Student
(and the same for Lectureres)
then from your UsersController you can do:
$this->User->Student->Country->findCountiesByCountry();
hope that helps
--
EDIT:
if you want to want to use $role instead of Student/Lecturer you would have to do it like this:
$this->User->{$role}->Country->findCountiesByCountry();
In the end I decided to just load counties in the user controller regardless of whether the form will need them or not since Admin is the only user that doesn't need them.
Try something like this:
public function setForForm() {
App::import('model', 'Country');
$Country = New Country();
$counties = $Country->getCountiesByCountry();
$homeCounties = $counties;
$termCounties = $counties;
$this->set(compact('homeCounties', 'termCounties'));
}
I don't know is this the best solution or not but it is working at least :)
Edited
Here is another mistake. Its not recommended to set variable from model to view , you can return data that will be set then in edit function normally set it to the view , but anyways if you need to set from model to the view you can load controller class to your model using App::import(); and use set function.

Categories