Laravel DB Select Query - laravel-5

I'm learning Laravel 5. Need help with query and print in blade.
I have one table with users info and one table with Steam info where I have user_id row.
How can I build this query:
SELECT username FROM steam WHERE id = user_id;
user_id is logged user in session
users table
id | email | username | password |
steam table
id | user_id | username | steam_id | avatar
Steam.php
<?php
namespace SGN\Models;
use SGN\Models\User;
use Illuminate\Database\Eloquent\Model;
use Invisnik\LaravelSteamAuth\SteamAuth;
class Steam extends Model
{
protected $table = 'steam';
protected $fillable = [
'user_id',
'username',
'avatar',
'steamid',
];
protected $hidden = [
'remember_token',
];
}
SteamController.php
<?php
namespace SGN\Http\Controllers;
use Auth;
use SGN\Models\Steam;
use Invisnik\LaravelSteamAuth\SteamAuth;
class SteamController extends Controller
{
private $steam;
public function __construct(SteamAuth $steam)
{
$this->steam = $steam;
}
public function login()
{
if ($this->steam->validate()) {
$user_id = Auth::user()->id;
$info = $this->steam->getUserInfo();
if (!is_null($info)) {
$user = Steam::where('steamid', $info->getSteamID64())->first();
if (is_null($user)) {
$user = Steam::create([
'user_id' => $user_id,
'username' => $info->getNick(),
'avatar' => $info->getProfilePictureFull(),
'steamid' => $info->getSteamID64()
]);
}
//Auth::login($user, true);
return redirect('/'); // redirect to site
}
}
return $this->steam->redirect(); // redirect to Steam login page
}
protected function create(array $data)
{
return Steam::create([
'username' => $data['username'],
'steamid' => $data['steamid'],
'avatar' => $data['avatar'],
]);
}
}
edit.blade.php
#section('content')
<h3>Update your profile</h3>
<div class="row">
<div class="col-lg-3">
Here print steam username from DB
</div>
</div>
#stop

Related

auth()->user()->pUserId makes Attempt to read property "pUserId" on null

I have a problem where i can't get the pUserId from database when using authentication
Here's the controller(Home Controller):
function index(){
$id = Auth::user()->pUserId; //Here's the main problem
$profiles = profiles::where('pUserId',$id)->first();
return view('home', compact('profiles'));
// return view('home');
}
auth.php(config):
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
]
User.php(model)(default by laravel):
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
protected $table = 'profiles';
protected $guarded = [''];
I've already tried without using controller and straight to .blade.php and the error is still the same
#auth
<div class="header-control">
{{ auth()->user()->pUserId }} //main problem
</div>
#endauth
The Error Display
Here's the route:
Route::get('/home', 'HomeController#index');
Route::get('/', 'LoginController#index')->middleware('guest');
Route::get('/login', 'LoginController#index')->middleware('guest');
Route::post('/login/authenticate', 'LoginController#authenticate')->middleware('guest');
Login Controller:
function authenticate(Request $request)
{
$login = $request->validate([
'pUserId' => 'required',
'password' => 'required'
]);
if(Auth::attempt($login))
{
$request->session()->regenerate();
return redirect()->intended('/home');
}
else
{
return back()->with('error', 'Wrong Login Details');
}
}
There's a several pUserId in profiles tables, but just said "property "pUserId" on null" when using
auth()->user()->pUserId or
$id = Auth::user()->pUserId;
Auth:attempt($login) is successfully working, i just don't understand it doesn't work in Home Controller
migrations:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->string('pUserId',5)->primary();
$table->string('pNamaLengkap', 255);
$table->enum('pJobDescription', ['Full Stack Developer','Backend Developer','Frontend Developer']);
$table->enum('pUnitKerja', ['Talent Management','Company Management','Customer Management']);
$table->enum('pDirectorate',['Human Resources','Company Profile','Stabilitas Sistem Keuangan','Sistem Pengelolaan','Pendukung Kebijakan']);
$table->string('password', 255);
$table->timestamps();
});
}
DB profiles
In your user model, specify the primary key if you don't use id as the primary key:
protected $primaryKey = 'pUserId';

Laravel Roles and Permissions based on Role specific Ability

I have a project in which I want a Specific page to be viewed by a specific user which have a role of viewing for example I have User 1 that has an Admin Role and the Admin Role has the Ability to View this page in my design I made 3 models Users, Roles, and Abilities
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;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','district','area','committee','position',
];
/**
* 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',
];
public function answer()
{
return $this->hasMany('App\Answer');
}
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function hasRole($role)
{
if ($this->roles()->where('name', $role)->first()) {
return true;
}
return false;
}
public function assignRole($role)
{
$this->roles()->save($role);
}
}
Role Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = ['name'];
public function abilities()
{
return $this->belongsToMany('App\Ability');
}
public function hasAbility($ability)
{
if ($this->abilities()->where('name', $ability)->first()) {
return true;
}
return false;
}
public function assignAbility($ability)
{
$this->abilities()->save($ability);
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
Ability Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ability extends Model
{
protected $fillable = ['name'];
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
This is my UserPolicy:
<?php
namespace App\Policies;
use App\User;
use App\Role;
use Illuminate\Auth\Access\HandlesAuthorization;
class UserPolicy
{
use HandlesAuthorization;
public function view (Role $role)
{
return $role->hasAbility('view');
}
public function manage (User $user)
{
return true;
}
public function edit (User $user)
{
return true;
}
public function update (User $user)
{
return true;
}
public function add (User $user)
{
return true;
}
}
And the Controller of The Policy
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\Role;
class MemberController extends Controller
{
public function index(Role $role)
{
$this->authorize('view', $role);
return view ('members.create')->with('users', User::all());
}
public function manage(User $user)
{
$this->authorize('manage', $user);
return view ('members.manage')->with('users', User::all());
}
public function edit(User $user)
{
$this->authorize('edit', $user);
return view ('members.edit')->with('user', User::all())->with('roles', Role::all());
}
public function update(Request $request, User $user)
{
$this->authorize('update', $user);
$user->roles()->sync($request->roles);
return redirect('/members/edit');
}
public function store(User $user)
{
$this->authorize('add', $user);
$this->validate(request(), [
'name' => ['required', 'string', 'max:255'],
'district' => ['required', 'string', 'max:255'],
'area' => ['required', 'string', 'max:255'],
'committee' => ['required', 'string', 'max:255'],
'position' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
$data = request()->all();
$member = new User();
$member->name = $data['name'];
$member->district = $data['district'];
$member->area = $data['area'];
$member->committee = $data['committee'];
$member->position = $data['position'];
$member->email = $data['email'];
$member->password = Hash::make($data['password']);
$member->save();
return redirect('/members/create');
}
}
The index function should be the one related to the function view in the UserPolicy
and this is the can located in my blade.php file
#can('view', \App\Role::class)
<li class="">
<a class="" href="/members/create">
<span><i class="fa fa-user-plus" aria-hidden="true"></i></span>
<span>Add Member</span>
</a>
</li>
#endcan
in the policy when I link it to the name of the role of the logged in user everything works just fine but if I want to link it to an ability of the role it doesn't work so any idea on how the View Function in the UserPolicy should be implemented ?
The first parameter that is passed to the policy is the authenticated User, not its Role. I don't think it works. Maybe if you reimplement using an EXISTS query.
public function view (User $user)
{
return $user->roles()->whereHas('abilities', function ($ability) {
$ability->where('name', 'view');
})
->exists();
}
->exists() turns the query into an EXISTS query, which will return a boolean value if the query finds anything without having to return any rows.
https://laravel.com/docs/7.x/queries#aggregates
You could put that logic into an User method.
# User model
public function hasAbility($ability): bool
{
return $this->roles()->whereHas('abilities', function ($ability) {
$ability->where('name', 'view');
})
->exists();
}
public function view (User $user)
{
return $user->hasAbility('view');
}

How to store the actual user logged into my database and display it as a created by field for my CRUD?

I have this code in my controller:
public function store(StoreRequest $request)
{
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
$request->validate([
'creado_por' => 'string'
]);
return ComprasNotificacionCancelacion::create([
'nombre' => request('nombre'),
'correo' => request('correo')
]);
}
This is the model:
protected $table = 'compras_notificacion_cancelacions';
protected $primaryKey = 'id';
protected $guarded = ['id'];
protected $fillable = [
'nombre',
'correo',
'creado_por'
];
protected $dates = [
'fecha_creacion',
'fecha_modificacion'
];
Could you help me, please?
Your question is not clear, but what you are trying to do is add logged in user as the creado_por here is how you can achieve that.
public function store(StoreRequest $request)
{
$request->validate([
'creado_por' => 'string'
]);
//here you can use either Auth()->user()->id or $request->user()->id
return ComprasNotificacionCancelacion::create([
'nombre' => $request->nombre,
'correo' => $request->correo,
'creado_por' => $request->user()->id
]);
}
additionally here are somethings you could improve. You can access same Auth()->user() from $request like $request->user().
You don't need the below codes.
$user = Auth::user();
$request->get('nombre');
$request->get('correo');
$request->get('creado_por');
$creado_por = Auth::user()->id;
and if using id as id no need to mention it
protected $primaryKey = 'id';
The way I store the author of an entry is that I have a created_by column in the database and I make sure that contains the right ID inside the model. Here's a trait I use, that I call CreatedByTrait.php and use it on the models that need it:
<?php namespace App\Models\Traits;
use Illuminate\Database\Eloquent\Model;
trait CreatedByTrait {
/**
* Stores the user id at each create & update.
*/
public function save(array $options = [])
{
if (\Auth::check())
{
if (!isset($this->created_by) || $this->created_by=='') {
$this->created_by = \Auth::user()->id;
}
}
parent::save();
}
/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function creator()
{
return $this->belongsTo('App\User', 'created_by');
}
}

Passing data to email view Laravel 5.3

I have this scenario in my app where I have to send user's password and username to their email right away after their account created by admin. Here is what I've done so far :
Controller :
public function store(Request $request) {
$data = $request->all();
$validasi = Validator::make($data, [
'name' => 'required|max:255',
'username' => 'required|max:255|unique:users',
'email' => 'required|email|max:150|unique:users',
'password' => 'required|confirmed|min:6',
'level' => 'required|in:admin,author',
]);
if ($validasi->fails()) {
return redirect('user/create')->withInput()->withErrors($validasi);
}
$data['password'] = bcrypt($data['password']);
$email = $data['email'];
Mail::to($email)->send(new UserAdded());
User::create($data);
return redirect('user');
}
The email will send successfully but I want to pass $data['username'] and $data['password'] to email view as well.
email view :
<div class="row">
<div class="col-sm-12 col-xs-12">
<h2><span>Welcome new User!</span></h2>
<p>Your username </p>
<p>Your password</p>
</div>
Mailable function :
class UserAdded extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
}
public function build()
{
return $this->view('email/newuser');
}
}
How to do it ? where will I define the $user data ? thanks for the help!
First of all, you need a class that builds the view. There you can define properties which you'll pass to the class. They'll be accessable in the view then.
<?php
namespace App\Mail;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class UserAdded extends Mailable
{
use Queueable, SerializesModels;
public $username;
public $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
public function build()
{
return $this->view('reference.your.view.path.here'); //CHANGE
}
}
You can now access the variables in your view.
<div class="row">
<div class="col-sm-12 col-xs-12">
<h2><span>Welcome new User!</span></h2>
<p>Your username: {{$username}} </p>
<p>Your password: {{$password}} </p>
</div>
Calling your view can be realized like this:
Mail::to($email)->send(new UserAdded($data['username'],$password));

Laravel Auth::attempt/login page isn't work properly

my registration page works finely .data is inserted properly into table called "registered_users".My login page is not work properly.
routes.php
<?php
Route::get('/', function()
{
return View::make('index');
});
//About page
Route::get('about', function()
{
return View::make('about');
});
//reister route
Route::get('register', function(){
return View::make('register');
});
Route::post('register_action', function()
{
$obj = new RegisterController() ;
return $obj->store();
});
Route::get('login', function(){
return View::make('login');
});
Route::post('logincheck', function(){
// username and password validation rule
$data = Input::except(array('_token')) ;
$rule = array(
'name' => 'required',
'password' => 'required',
) ;
$message = array(
'password.required' => 'The Password field is required.',
'name.required' => 'The Username is required.',
);
$v = Validator::make($data,$rule);
if ($v->fails()) {
// username or password missing
// validation fails
// used to retain input values
Input::flash ();
// return to login page with errors
return Redirect::to('login')
->withInput()
->withErrors ($v->messages ());
} else {
$userdata = array (
'name' => Input::get('name'),
'password' => Input::get('password')
);
//var_dump($userdata);
If (Auth::attempt ($userdata)) {
// authentication success, enters home page
return Redirect::to('home');
} else {
// authentication fail, back to login page with errors
return Redirect::to('login')
->withErrors('Incorrect login details');
}//end if
}//end of v else
});
// Route::get ('home',function(){
// return View::make('home');
// });
Route::get ('test',function(){
return View::make('test');
});
Route::group (array ('before' => 'auth'), function () {
Route::get ('home',function(){
return View::make('home');
});
});
Route::get ('logout',function(){
Auth::logout ();
return Redirect::to('login');
});
i checked Route::post('logincheck', function() in routes.php step by step ...everything is ok...but following part of Route::post('logincheck', function() in routes.php is not work properly .whether i enter correct name and password or wrong in log in form ,it just shows 'Incorrect login details' message
If (Auth::attempt ($userdata)) {
// authentication success, enters home page
return Redirect::to('home');
} else {
// authentication fail, back to login page with errors
return Redirect::to('login')
->withErrors('Incorrect login details');
}//end if
login.blade.php
#extends('layout')
#section('main')
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registrationhhjh</title>
</head>
<body>
<section class="header">
<div class="bannner"> </div>
<div class="container">
<h1>Sign In</h1>
#if ($errors->any())
<ul style="color:red;">
{{ implode('', $errors->all('<li>:message</li>')) }}
</ul>
#endif
{{ Form::open(array('url' => 'logincheck')) }}
{{ Form::text('name', '', array('placeholder'=>'Name')) }}<br><br>
{{ Form::password('password', '', array('placeholder'=>'Password')) }}<br><br>
{{ Form::submit('Sign in', array('class'=>'btn btn-success')) }}
<!-- {{ Form::submit('register', array('class'=>'btn btn-primary')) }} -->
{{ HTML::link('register', 'Register', array('class' => 'btn btn-info'))}}
{{ Form::close() }}
</div>
</section>
</body>
</html>
#stop
User.php(model).i think may be there is problems in User.php(model)
<?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 = 'registered_users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
//protected $hidden = array('password');
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return "remember_token";
}
public function getReminderEmail()
{
return $this->email;
}
}
auth.php..can anyone tell me what is 'table' => 'users', in auto.php?....once i rename it as 'table' => 'registered_users' because i have no 'users' named table.but the problem remain (same i can not go to 'home page' )
<?php
return array(
/*
|--------------------------------------------------------------------------
| Default Authentication Driver
|--------------------------------------------------------------------------
|
| This option controls the authentication driver that will be utilized.
| This driver manages the retrieval and authentication of the users
| attempting to get access to protected areas of your application.
|
| Supported: "database", "eloquent"
|
*/
'driver' => 'eloquent',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
'model' => 'User',
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
'table' => 'users',
/*
|--------------------------------------------------------------------------
| Password Reminder Settings
|--------------------------------------------------------------------------
|
| Here you may set the settings for password reminders, including a view
| that should be used as your password reminder e-mail. You will also
| be able to set the name of the table that holds the reset tokens.
|
| The "expire" time is the number of minutes that the reminder should be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
*/
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
i use wamp server..i use laravel 4.2..my database name is mydb...table name
registered_users
table has id,name,email,password,remember_token,created_at,updated_at fields
remember_token field type is varchar(270)...is there is any limitation in remember_token size
please help me anyone what is the problem in login system?
Here is my RegisterController.php
<?php
class RegisterController extends BaseController {
/*
|--------------------------------------------------------------------------
| Default Home Controller
|--------------------------------------------------------------------------
|
| You may wish to use controllers instead of, or in addition to, Closure
| based routes. That's great! Here is an example controller method to
| get you started. To route to this controller, just add the route:
|
| Route::get('/', 'HomeController#showWelcome');
|
*/
// public function store()
// {
// Register::saveFormData(Input::except(array('_token')));
// }
public function store()
{
$data = Input::except(array('_token')) ;
$rule = array(
'name' => 'required|unique:registered_users',
'email' => 'required|email|unique:registered_users',
'password' => 'required|min:6|same:cpassword',
'cpassword' => 'required|min:6'
) ;
$message = array(
'cpassword.required' => 'The confirm password field is required.',
'cpassword.min' => 'The confirm password must be at least 6 characters',
'password.same' => 'The :attribute and confirm password field must match.',
);
$validator = Validator::make($data,$rule,$message);
// $validator = Validator::make($data,$rule);
if ($validator->fails())
{
return Redirect::to('register')
->withErrors($validator->messages());
}
else
{
Register::saveFormData(Input::except(array('_token','cpassword')));
return Redirect::to('register')
->withMessage('Successfully registered');
}
}
}
Here is model/Register.php
<?php
class Register extends Eloquent {
protected $guarded = array();
protected $table = 'registered_users'; // database table name
public $timestamps = 'false' ; // to disable default timestamp fields
// model function to store form data to database
public static function saveFormData($data)
{
DB::table('registered_users')->insert($data);
}
}
Finally i solved my problem.My problem is that i stored my password as plaintext.for solving my problem i just edited my models\Register.php file .
Here is my edited models\Register.php
<?php
class Register extends Eloquent {
protected $guarded = array();
protected $table = 'registered_users'; // database table name
public $timestamps = 'false' ; // to disable default timestamp fields
// model function to store form data to database
public static function saveFormData($data)
{
// DB::table('registered_users')->insert($data);
$name = Input::get('name');
$email = Input::get('email');
$password = Hash::make(Input::get('password'));
$user = new User;
$user->name = $name;
$user->email = $email;
$user->password = $password;
$user->save();
}
}
The Auth::attempt() function automatically hashes your password. The problem is that you are storing your passwords as plain text. So when the method checks if your password is correct, it hashes it and compares it to the saved password. That password is not hashed, so it wont work unless you hash your password upon registry.

Resources