使用用户名从laravel中的数据库获取数据

时间:2014-11-14 02:21:00

标签: php mysql laravel

我在数据库中有一个名为'User'的表。我想要的只是获取用户的基本信息。我试图从数据库中获取数据,但让我烦恼的是我获取了表中的所有数据。 UserTable

|id|username|firstname|lasttname|middlename|gender|age|birthdate|address|contact_number|designation|
 1   admin    lee       chiu      kim        male  47   07-22-87  cebu     0977452445    admin
 2   lrose    rose       loo      mar       female 27   04-02-88  cebu     0977452445    manager
 3   mgray    gray       men      try        male  37   01-22-89  cebu     0977452445    employee

UserProfile.php - >模型

<?php 
    class UserProfile  extends Eloquent   {
        public $timestamps=false;
        protected $table = 'users';
        protected $fillable=array('firstname','lastname', 'middlename', 'gender', 'age', 'birthdate', 'address', 'contact_number', 'designation');
    }

这是我网站的模型。

UserProfileContoller.php - &gt;控制器

<?php
class UserProfileController extends \BaseController {
    public function index($id)
    {
        $userprofile = User::find($id);

        return View::make('userprofile.index', array('userprofile' => $userprofile));

        //return View::make('userprofile.index')->with('UserProfiles',UserProfile::get());
    }

例如,我目前登录用户名admin,我想编辑和查看我的个人资料。如何仅为管理员获取数据。请帮助。

她的情况是这样的。假设他们有3名员工。所以在表3中的用户名。我假设我不是管理员。我将使用lrose登录。另一个以admin和so.on登录如果我们三个人将转到我们的个人资料,唯一显示的是他们自己的个人资料并可以编辑它。

4 个答案:

答案 0 :(得分:2)

假设您为数据库设置属性,为什么不使用DB对象?

 // In the User table find the item with the username 'admin'
 DB::table('User')->where('username', '=', 'admin')->get();

获取某些已登录用户的信息(假设您拥有其用户名),称为$userprofile。然后我们需要做的就是find按ID然后获取username

 // $id is the ID of the logged in user
 $userprofile = User::find($id)->username; // get username of logged in user

答案 1 :(得分:0)

$ userprofile :: find($ id)只会获取admin的信息,如果$ id = 1。

find()只返回数据库中的1个元组。

调用find()后,您可以访问数据:

$userprofile->firstname

答案 2 :(得分:0)

你的意思是当你将$ id传递给用户控制器的索引方法时,会返回其他用户的所有数据吗?

这有点奇怪。

  1. $ userprofile = User :: find($ id);将该行更改为$ userprofile = User :: find(1);并查看您是否只能获取admin的数据。
  2. 如果没有,可能是你在调用其他方法。可能你会在其他地方迭代索引方法多次,这样你就可以获得数据库中的所有数据。要确认这两种可能性,只需在索引方法的入口点添加echo'我在'。如果没有显示回显消息,则第一种可能性为真。如果出现多个回显消息,则第二种可能性为真。
  3. 希望这有帮助。

答案 3 :(得分:0)

首先,您需要在登录后使用Session并将id用户名存储在会话中。

e.g。

第1步:

if($login) //successfull login
{
    Session::put('userid', $userid);
    //this id, you have to retreive it from the database after successful login
}

第2步:

设置route

Route::get('profile',['uses' => 'UserProfileContoller@index']);

第3步:

控制器

public function index()
{
     if(is_null(Session::get('userid'))) return Redirect::to('login');

     return View::make('userprofile.index', ['userprofile' => $this->model->index()]);
     // Above code uses dependency injection to retrieve the information from db.
}

第4步:

UserProfileModel

public function index()
{
    return DB::table('user')->where('id','=', Session::get('userid'))->first();
}

p.s. i find it easier to use query builder than eloquent orm. if you want to use orm, change the code where needed.