Entrust not finding user's roles - laravel

I have the following in my controller method that returns JSON to my view:
public function RolesForUser()
{
$userid = Input::get('userid');
$assigned = DB::table('assigned_roles')
->select(array('role_id'))
->where('user_id', '=', $userid)
->get();
$user = User::find($userid);
$roles = $user->roles();
$data = array('assigned' => $assigned, 'roles' => $roles);
return Response::json($data);
}
Returns the following (inspected using Fiddler):
{"assigned":[{"role_id":"2"},{"role_id":"3"},{"role_id":"4"}],"roles":{}}
The SQL statement that uses Query Builder returns the correct results, but the method that uses Entrust (copied from Entrust Issue 34, after making the change to my User model) doesn't return any roles.
I also tried the solution in this SO question, but it just gives my an SQL error.
Any ideas where I'm going wrong, I'm on Laravel 4.2.11?
My User model:
class User extends Eloquent implements UserInterface, RemindableInterface
{
use HasRole;
/**
* 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');
protected $primaryKey = 'UserID';
public $timestamps = false;
/*Standard methods removed for brevity*/
public function roles()
{
return $this->hasMany('Role');
}
}

It looks like you have a roles method defined that should not be defined. The use of the Trait HasRole already adds the roles relationship to the User model.
Take a look at the other stuff that the HasRole adds to your model: https://github.com/Zizaco/entrust/blob/master/src/Entrust/HasRole.php
The roles() method returns a relationship. It is recommended to return ->roles or ->roles()->get().
Hope this helps.

Related

getting error when applied WHERE clause on a model(parent) and then gets its related model(child) data in eloquent

I have a User model which is a parent and Project model which is a child. I created a one-to-many relationship between these two like below.
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'email', 'password',
];
/**
* 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 projects(){
return $this->hasMany('App\Project', 'user_id');
}
}
Project Model:
class Project extends Model
{
// Table Name
protected $table = 'projects';
//Primary Key
protected $primaryKey = 'project_id';
// Timestamps
public $timestamps = true;
protected $guarded = [];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
when applying where clause on user model and then getting its related projects:
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::where('email', $request->input('client'))->projects;
}
}
getting error
Exception
Property [projects] does not exist on the Eloquent builder instance.
but when doing
$client = User::find(id)->projects;
above query is giving me results.
Result Expected: i want to get the User model data by WHERE() clause instead of Find() clause and then gets its related projects.
As the Error Says that you dont have property in the Builder
$client = User::where('email', $request->input('client'))->projects;
try this
$client = User::with('projects')->where('email', $request->input('client'))->first()->projects;
here we are getting the user with the specific email and loading the realtion and here you get the relation as object
The source of your issue is that you have not yet retrieved any users. Before calling first() or get() on the query builder, you are limited to functions of the query builder.
Short version: call first() before accessing the projects
$client = User::query()
->where('email', $request->input('client'))
->first()
->projects;
Optional: add with('projects') to eager load the projects. This doesn't add any performance bonus in your case though, as you are only loading a single model.
class HomeController extends Controller
{
public function createProject(Request $request){
$client = User::with('projects')->where('id');
}
}
In HomeController this line will retrun collection of array.... In simple words it will return multiple records....
$client = User::where('email', $request->input('client'))->projects;
As you want single record use first (). To retrive single record... It will retrun first matching record...
$client = User::where('email', $request->input('client'))->first()->projects;

Laravel Eloquent Create

Hello so I've started using Laravel and it is useful and easy. For now I have a CRUD in which is working. In my AccountController#store the code is:
public function store(Request $request)
{
$input = $request->all();
Accounts::create($un);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
This basically adds a new account in my table. My problem is, I have a password textbox and I can't hash it since this code automatically gets every input in the form. How can I get it one by one? Like username, email and password only so I can hash the password.
You could get the input one by one and then hash the password and save it to the database. But that would require extra code.
You could also add an extra function to your Account model that will take care of this automatically.
Take a look at the example I use to create my management users.
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Hash;
class Management extends Model implements AuthenticatableContract {
use Authenticatable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'Management';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Automatic hash function for the password.
*
* #var array
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
}
Regarding your code, you could do this:
public function store(Request $request)
{
Accounts::create($request->all());
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
Make sure to modify the example model above to your own needs!
You can also do:
public function store(Request $request)
{
$input = $request->all();
Accounts::create([
'username' => $input['username'],
'password' => bcrypt($input['password']),
]);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
You call Input::all() to get all the attributes passed in, and Input:get('key') to get a specific key.
So you should call:
$account = new Accounts;
$account->username = Input::get('username');
$account->password = Hash::make(Input::get('password'));
//key with a default
$account->password = Input::get('age', 20);
//optional field
if (Input::has('optional')) {
$account->optional = Input::get('optional');
}
//any other fields that account needs
$account->save()

Eloquent ORM all() not returning anything

Shoot me down if I this is a silly question, but I am really struggling to get this all() function working for me. It is returning empty list for me. Any help will be highly appreciated. I have got 2 rows in the newsletters table
Model looks like this -
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Newsletters extends Eloquent {
//use UserTrait, RemindableTrait;
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'newsletters';
/**
* The attributes excluded from the model's JSON form.
*
* #var array */
protected $guarded = array('newsletterId');
protected $fillable = array('name', 'subject','from_email','from_name');
public static $rules = array(
'name' => 'required|min:5',
'subject' => 'required|min:5',
'from_email' => 'required|email',
'from_name' => 'required'
);
}
My call in the controller is like this -
<?php
class newslettersController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//$newsletters = Newsletters::paginate(3);
$newsletters = Newsletters::all();
echo $newsletters;exit();
return View::make('newsletters.index', compact('newsletters'));
}
Any value - even 0000-00-00 00:00:00 - in the deleted_at column tells Laravel that the item has been deleted. Change your default value for that column to NULL or new items will be flagged as deleted on creation.
The $table->softDeletes() Schema function does this automatically if you use it in a migration.
As soon as you use the SoftDeletingTrait a global scope will be applied to every query with your model so all records where deleted_at is not NULL will be ignored.
Illuminate\Database\Eloquent\SoftDeletingScope:
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->whereNull($model->getQualifiedDeletedAtColumn()); // <<-- this
$this->extend($builder);
}
Change the default of your deleted_at column to NULL and update the existing records to be NULL as well.
If you are sure newsletters is the correct table name as #Ray said.
Try this:
$newsLetters = DB::table('newsletters')->get();

Laravel Resource Router ignoring eager loaded data and getting a new query

In my resource router, I have this function, which is supposed to eager load only the rows that have the configureName of $id. The problem is that when I call $demo->demoSettings resource router is ignoring my eager load and grabbing all of the demoSettings related to this $demo.
This isn't the only instance of this problem that I have. I also have a couple loops where I am injecting data into my api index from related tables for convenience purposes. The moment I add a call to access my eager loaded data, it queries again and injects the data into my resource return. I've worked around it by using unset in the other instances, but this one is different because I actually want the list of data, rather than a single value.
public function show($demoId,$id)
{
$demo = Demo::with(array('DemoSettings' => function($query) use ($id)
{
$query->where('configureName', '=', $id);
}))->where('demoId','=',$demoId)->first();
return $demo->demoSettings;
}
Demo Model
class Demo extends Eloquent {
protected $table = 'Demo';
public $timestamps = false;
/**
* The key column used by the model.
* #var string
*/
protected $primaryKey = 'idDemos';
/**
* one(demo) to many(demoSettings) relationship
* #return array of the demoSettings associated with the demo
*/
public function demoSettings()
{
return $this->hasMany('DemoSettings','idDemos','idDemos')->orderBy('configureName','asc');
}
}
DemoSettings Model
class DemoSettings extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'DemoSettings';
/**
* The key column used by the model.
* #var string
*/
protected $primaryKey = 'idDemoSettings';
/**
* many(demoSettings) to one(demo) relationship
* #return demo the parent record
*/
public function demo()
{
return $this->belongsTo('Demo','idDemos','idDemos');
}
}
Route
Route::group(array('prefix' => 'api/v1'), function(){
Route::group(array('prefix' => 'demos'), function(){
Route::resource('/', 'api_DemosController', array('only' => array('index','store','destroy','show')));
Route::resource('/{demoId}/settings', 'api_DemoSettingsController', array('only' => array('index','store','show')));
});
});

pivot table in laravel 4 insertion

hey guys im new in laravel and i was trying to insert into my pivot table. i have this structure in my database
the departments table belongs to many categories and same as category so i have this models
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
protected $fillable = ['department_name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function categories()
{
return $this->belongsToMany('Categories');
}
}
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Categories extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function department()
{
return $this->belongsToMany('Departments');
}
}
then i have a query in my controller like this
$messages = array(
'required' => 'Please Fill the required field',
'unique' => 'Name Already exist'
);
$catName = Input::get('categoryName');
$deptId = Input::get('deptId');
$validation = Validator::make(Input::all(),[
'categoryName' => 'required|unique:categories,name' ], $messages);
if($validation->fails()){
return array('error' =>$validation->messages()->all() );
}else{
$findDepartment = Departments::find($deptId);
$saveCat = $findDepartment->categories()->insert(array('name' => $catName));
}
but then when i checked the tables it adds up on the categories table but nothing is added in the category_department. do i miss any codes? and also i had an error last time I was trying to migrate my pivot table the error was this.
can you help me guys on what i am missing? tnx for the help in advanced.
First, you should name your model classes as singular: Category, Department.
Then try to declare your relationships with the pivot table name:
public function categories()
{
return $this->belongsToMany('Category', 'category_department');
}
and
public function departments()
{
return $this->belongsToMany('Departments', 'category_department');
}
now, to insert new data, try attach:
$findDepartment = Department::find($deptId);
$category = Category::where('name', '=', $catName)->first();
$saveCat = $findDepartment->categories()->attach($category->id);

Resources