laravel inserting into multiple tables - php

I have 2 tables
#something - id, name, url
#something_users - id, id_something, email, password
My models
class Something extends Eloquent
{
protected $table = 'something';
protected $fillable = ['name', 'email', 'password'];
public $errors;
public function User()
{
return $this->belongsTo('User', 'id', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function Something()
{
return $this->belongsTo('Something');
}
}
Controller
$input = Input::all();
// also some validation
$this->db->fill($input);
$this->db->password = Hash::make(Input::get('password'));
$this->db->push();
$this->db->save();
SQL
insert into `something` (`name`, `email`, `password`) values...
I need to insert name into the first table(something) and email, password into second(something_users)
How to do that? I have on clue about that.

Your relationships are a little screwed up, you probably want to change those. Note the hasMany() vs the belongsTo(). If a something can only have one user, you may wish to change the function to hasOne() from hasMany() and the name of the function to user() only because it makes more sense that way.
class Something extends Eloquent {
protected $table = 'something';
public function users()
{
return $this->hasMany('User', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function something()
{
return $this->belongsTo('Something', 'id_something');
}
}
And then to save a something and a user and have them linked, it's pretty easy.
$something = new Something;
$something->name = Input::get('name');
$something->url = Input::get('url');
$something->save();
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$something->users()->save($user);
I'm not seeing your constructor so I don't know which model $this->db refers to, but you may want to replace the somethings or users depending on what you have. To keep your dependency injection going, I'd suggest naming your dependencies what they actually are.
class SomeController extends BaseController {
public function __construct(User $user, Something $something)
{
$this->user = $user;
$this->something = $something;
}
public function someFunction()
{
$this->something->name = Input::get('name');
$this->something->url = Input::get('url');
$this->something->save();
$this->user->email = Input::get('email');
$this->user->password = Hash::make(Input::get('password'));
$this->something->users()->save($this->user);
}
}

Laravel 6.
I want to add data to users table and customer table using one controller that is RegisterController.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Customer;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
//this part is my code
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role' => '2',
]);
$customer = Customer::create([
'user_id' => $user['id'],
'firstname' => $data['name'],
'lastname' => $data['name'],
'email' => $data['email'],
'address' => '',
'phone' => '',
'gender' => '',
]);
return $user;
}
}
enter image description here
enter image description here
This answer is not the best one, because this answer is just a shortcut code so that my code is not error. maybe another error will appear in the future.
but I hope my answer can solve your problem

Related

Relate a new user to a role from their registration Laravel

I have an app in laravel and I have 3 Admin, owner, user roles, I want that when a user registers he can choose between user and owner, for now I will use the registry of laravel / ui, I will leave them my relationships and my tables
Model Role
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
public function roles(){
return $this->belongsToMany('App\Role');
}
/* Validations */
// The roles are received in the authorizeRoles variable, and they are validated if my role is valid or not, when accessing a page, the helpers abort generates an http exception and the user receives an error
public function authorizeroles($roles){
if($this->hasAnyRole($roles)){
return true;
}
abort(401,'This action is unauthorized');
}
// Function, where we iterate (HasAnyRole) Enter the roles to check if you have any role
public function hasAnyRole($roles){
if(is_array($roles)){
foreach($roles as $role){
if($this->hasRole($role)){
return true;
}
}
}else{
if($this->hasRole($roles)){
return true;
}
}
return false;
}
// HasRole function - We validate if our user contains the role for which it is asked -->
public function hasRole($role){
if($this->roles()->where('name',$role)->first()){
return true;
}
return false;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'provider', 'provider_id'
];
/**
* 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',
];
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
I would like to know how to filter between only two roles in my controller and paint them in my view in a select, I would appreciate your support
In Controller
$roles = Role::whereIn('name', ['owner', 'user'])->get();
//And pass this roles in your view for example:
return view('user.create', compact('roles');
In view, in form:
<select name='role_id'>
#foreach($roles as $role)
<option value="{{$role->id}}">{{$role->name}}</option>
#endforeach
</select>

Laravel 5.3 get last insert id after registration

Using laravel5.3
php 5.6.3
I want the last inserted id in users table for the redirected page after registration
So I want the last inserted id to userprofileadd.blade.php
I have also tried ->with('id', $user->id) from register function
I don't want automatic login after registration , so I removed the login part , and after registration the user will be redirected to another form , and i want the latest user id (who ever registered) from users table
Register controller:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\role;
use App\Userdetails;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/userprofileadd';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth', 'hr']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'role'=>'required'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
}
public function showregistrationform()
{
$roles = role::all(); // get all teams
return view('auth.register', [ 'roles' => $roles]);
}
}
register function (i have commented out login after registration)
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
// $this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
// ->with('id', $user->id)
}
if you are using model then
$user = new User();
$user->name = "JOHN";
$user->save();
$user->id; // contain the inserted id
if you are using db class
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
To get the last created user
$user = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
$this->lastCreatedUserId = $user->id;
To pass the userId to custom redirection page
You may use the Laravel Auth redirectTo method. Doc.
protected function redirectTo()
{
return route('customroutename', ['id' => $this->lastCreatedUserId]);
}
Example:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\role;
use App\Userdetails;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
public $lastCreatedUser;
use RegistersUsers;
protected $redirectTo = '/userprofileadd';
//The redirectTo method will take precedence over the redirectTo attribute.
protected function redirectTo()
{
//assuming your route name is 'userprofileadd' if not, use your route name of the route('/userprofileadd')
return route('userprofileadd', ['id' => $this->lastCreatedUser]);
}
public function __construct()
{
$this->middleware(['auth', 'hr']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'role'=>'required'
]);
}
protected function create(array $data)
{
$user = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
$this->lastCreatedUser = $user->id;
return $user;
}
public function showregistrationform()
{
$roles = role::all(); // get all teams
return view('auth.register', [ 'roles' => $roles]);
}
}
You can access the last created user in your UserprofileController's index method like,
public function index($id)
{
$lastCreatedUser = $id;
//you may pass this variable to the view
}
Hope it helps.. Let me know the results..
I'm not sure if this is what you're looking for or not, but you can do this to retrieve the latest record in the users table:
$latestUser = App\User::latest()->first();
Hopefully this helps.

Laravel Auth::attempt() not actually login

When I am taking an attempt to login it just redirecting to "admin" page with any value. I did all the possible try found in google. But still not having luck. I am badly in need of help. My code is given below :
Controller: LoginController.php
<?php
class LoginController extends BaseController {
public function doLogin()
{
$rules = ['username'=>'required','password'=>'required'];
$credentials = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$validation = Validator::make($credentials, $rules);
if($validation->fails()){
return Redirect::back()
->withInput()
->withErrors($validation);
}
else{
Auth::attempt($credentials);
return Redirect::intended('admin');
}
}
public function doLogOut()
{
Auth::logout();
return Redirect::to('/login');
}
}
Model: User.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
UserTableSeeder:
<?php
class UserTableSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$vader = DB::table('users')->insert([
'username' => 'admin',
'password' => Hash::make('admin'),
'created_at' => new DateTime(),
'updated_at' => new DateTime()
]);
}
}
Routes:
Route::post('login','LoginController#doLogIn');
Let's take a closer look at these lines:
else {
Auth::attempt($credentials);
return Redirect::intended('admin');
}
What you're doing in this snippet is
You try to log the user in.
Then you redirect, regardless of whether it worked or not.
If you want to make sure the user is actually logged in, you should wrap the attempt within an if clause.

Laravel/Ardent - on save(), error: Relationship method must return an object of type Illuminate

I'm having some trouble getting my Laravel relationships to work out. In my application, there is a one-to-many relationship between users and ideas. (A user may have multiple ideas.) I'm using Ardent.
Here's my User model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
use LaravelBook\Ardent\Ardent;
class User extends Ardent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
protected $fillable = array('first_name', 'last_name', 'email', 'password');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHashPasswordAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $passwordAttributes = array('password');
public static $rules = array(
'first_name' => 'required|between:1,16',
'last_name' => 'required|between:1,16',
'email' => 'required|email|unique:users',
'password' => 'required|between:6,100'
);
public function ideas()
{
return $this->hasMany('Idea');
}
}
And here's my Idea model:
use LaravelBook\Ardent\Ardent;
class Idea extends Ardent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'ideas';
protected $fillable = array('title');
public $validation_errors;
public $autoPurgeRedundantAttributes = true;
public $autoHydrateEntityFromInput = true;
public static $rules = array(
'title' => 'required'
);
public function user()
{
return $this->belongsTo('User');
}
}
Finally, here's my controller code:
class IdeasController extends BaseController {
public function postInsert()
{
$idea = new Idea;
$idea->user()->associate(Auth::user());
if($idea->save())
{
return Response::json(array(
'success' => true,
'idea_id' => $idea->id,
'title' => $idea->title),
200
);
}
else
{
return Response::json(array(
'success' => false,
'errors' => json_encode($idea->errors)),
400
);
}
}
}
$idea->save() throws the error:
{
"error": {
"type": "LogicException",
"message": "Relationship method must return an object of type Illuminate\\Database\\Eloquent\\Relations\\Relation",
"file": "\/var\/www\/3os\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Eloquent\/Model.php",
"line": 2498
}
}
At first, I was trying to set the user_id in the Idea like so:
$idea->user_id = Auth::id();
I then changed it to:
$idea->user()->associate(Auth::user());
But the results were the same.
Any suggestions would be much appreciated.
You cannot use associate in that direction, since it can only be used on a belongsTo relationship. In your case, an idea belongs to a user and not the other way around.
I suspect there is an error when saving, as you create an idea without the required title, and you then try to get the errors by calling $idea->errors, while it should be $idea->errors().
associate will work on belognsTo relationship , in your cause what you have to use is Attaching A Related Model. See more about Attaching A Related Mode in documentation.

Access to undeclared static property: User::$rules in laravel

public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, User::$rules);
if ($validation->passes())
{
$user = User::find($id);
$user->update($input);
return Redirect::route('users.show', $id);
}
return Redirect::route('users.edit', $id)
->withInput()
->withErrors($validation)
->with('message', 'There were validation errors.');
}
this is what the code i am having, when I attempt to update a record it shows the following error message. Access to undeclared static property: User::$rules
the user model as follows
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
I imagine you have a property in your User model like this:
<?php
class User extends Eloquent {
public $rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
);
}
This is a class instance property, but you’re trying to access it statically (the error messages tells you such).
Simply add the static keyword to the property:
<?php
class User extends Eloquent {
public static $rules = array(
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
);
}

Categories