I have a class User that extends
<?php
namespace App;
class User extends \Cartalyst\Sentinel\Users\EloquentUser
{
public function chalets(){
return $this->hasMany('App\Chalet');
}
}
and i have Chalet Class
class Chalet extends Model
{
protected $fillable = [
'name', 'description',
];
public function user(){
return $this->belongsTo('App\User');
}
}
And i have method to add chalet by user :
public function postCreateChalet(Request $request){
$chalet = new Chalet([
'name' => $request->input('name'),
'description' => $request->input('description')
]);
Sentinel::getUserRepository()->setModel('App\User');
$user = Sentinel::getUser();
$user->chalets()->save($chalet);
return ('chalet has created');
}
and its give me an error :
BadMethodCallException
Call to undefined method Cartalyst\Sentinel\Users\EloquentUser::chalets()
Is it a right way to extend User class ?
I have searched for ways to extend the User class. I found this question:Model Inheritance in Laravel didn't help me though.
I'm using Laravel 5.7
The exception you're getting indicates Sentinel is still referring to the default stock Sentinel's EloquentUser model. Make sure you point to your extended user model with the published Sentinel configurations.
Run the below command
php artisan vendor:publish --provider="Cartalyst\Sentinel\Laravel\SentinelServiceProvider"
Open up the published config file at 'config\cartalyst.sentinel.php'
Modify it from the below content:
'users' => [
'model' => 'Cartalyst\Sentinel\Users\EloquentUser',
],
to:
'users' => [
'model' => 'App\User',
],
For more information, refer to https://github.com/cartalyst/sentinel/wiki/Extending-Sentinel
You won't need the following line after you configured it via config:
Sentinel::getUserRepository()->setModel('App\User');
Related
The code for the policy is here:
class userOwnedClassPolicy
{
use HandlesAuthorization;
...
public function create(User $user)
{
return ($user->userType == 'teacher');
}
...
}
This policy is registered thusly in the AuthServiceProvider.php file:
class AuthServiceProvider extends ServiceProvider
{
//Map models to authorization policies.
protected $policies = [
App\Models\classMember::class => App\Policies\classMemberPolicy::class,
App\Models\evaluation::class => App\Policies\evaluationPolicy::class,
App\Models\group::class => App\Policies\groupPolicy::class,
App\Models\groupMember::class => App\Policies\groupMemberPolicy::class,
App\Models\sharedClass::class => App\Policies\sharedClassPolicy::class,
App\Models\slg::class => App\Policies\slgPolicy::class,
App\Models\spreadsheet::class => App\Policies\spreadsheetPolicy::class,
App\Models\spreadsheetValue::class => App\Policies\spreadsheetValuePolicy::class,
App\Models\teacher::class => App\Policies\teacherPolicy::class,
App\Models\test::class => App\Policies\testPolicy::class,
App\Models\userOwnedClass::class => App\Policies\userOwnedClassPolicy::class
];
public function boot()
{
$this->registerPolicies();
}
}
(I have tried registering the policies using strings of the file paths as well, but this accomplishes nothing.)
The relevant section of controller code is here:
class ClassController extends Controller
{
...
public function store(Request $postReq)
{
$this->authorize('create', Auth::user());
userOwnedClass::create([
'name' => $postReq->input('className'),
'ownerId' => Auth::user()->id
]);
}
...
}
I have tried substituting the code in the policy's create method with return true, but even that fails. What have I done wrong, and why does the controller always return a 403 error when called?
As you created policy userOwnedClassPolicy and set it for userOwnedClass model in AuthServiceProvider here:
App\Models\userOwnedClass::class => App\Policies\userOwnedClassPolicy::class
you cannot just run policy method:
$this->authorize('create', Auth::user());
When you run this line above, you tell - check create method for policy for \App\Models\User object, but you don't have any policy created for this model.
So in this case you should run it like so:
$this->authorize('create', \App\Models\userOwnedClass::class);
Then Laravel will know that it should run create method from userOwnedClassPolicy policy and it will automatically pass currently authenticated user into $user variable in policy method.
controller code : code for controller works for Employers pagination but unable to work pagination about Stories controller.
public $paginate = [
'Employers' => ['scope' => 'employer'],
'Stories' => ['scope' => 'story']
];
public function index()
{
// Paginate property
$this->loadComponent('Paginator');
// In a controller action
$stories = $this->paginate($this->Stories, ['scope' => 'story']);
$employers = $this->paginate($this->Employers, ['scope' => 'employer']);
pr($stories);
$this->set(compact('employers', 'stories'));
}
Model code: model description stand same for all model as yet but understand that model definition unable to work for stories model but as we progress with model definition about employers table that works absolutely fine.
<?php
// src/Model/Table/EmployersTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class EmployersTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp');
}
}
<?php
// src/Model/Entity/Employer.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Spk extends Entity
{
protected $_accessible = [
'*' => true,
'id' => false,
'slug' => false,
];
}
<?php
// src/Model/Table/StoriesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class StoriesTable extends Table
{
public function initialize(array $config): void
{
$this->addBehavior('Timestamp');
}
}
<?php
// src/Model/Entity/Story.php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Sty extends Entity
{
protected $_accessible = [
'*' => true,
'id' => false,
'slug' => false,
];
}
Bug i keep looking at as i get through load page action i face that Employers data called but Stories data unable to load. Suggestions are open to view look forward to your answers.
error message:
Undefined property: EmployersController::$Stories in /Applications/MAMP/htdocs/sd/sd/src/Controller/EmployersController.php
Surely it's possible, the feature is explicitly documented. The error has nothing to do with pagination, it simply means that the property that you're trying access ($this->Stories) doesn't exist.
Controllers only have one default model that is being loaded automatically, and that's the model that matches the controller name according to the conventions, so in your EmployersController that's the Employers model. Additional models need to be loaded manually:
$this->loadModel('Stories');
// ...
$stories = $this->paginate($this->Stories, ['scope' => 'story']);
See also
Cookbook > Controllers > Loading Additional Models
No, That is not possible as CakePHP only works for single table with multiple pagination query request to same model. But doesn't not apply to many models.
I've created a multi auth test in Laravel 5.4. It's using custom middlewares, custom Eloquent providers, etc. The auth flow is working, I can login in both ways. But if the user is signed in, in the home controller when I want to check the user with Auth::user() or Auth::guard()->user(), it's empty. The Auth::guard() is empty as well. But I don't understand, why?! It should contains the signed in user instance, shouldn't it?
Also the $request->getUserResolver() says that the guard is null... o.O
What did I do wrong?
Here it is my test repo, if you want to check my code.
Thank you in advance!
Edit 1:
In the \app\Http\Controllers\Employee\HomeController.php the Auth::guard()->user() and the Auth::user() are empty.
namespace App\Http\Controllers\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HomeController extends Controller
{
public function __construct(Request $request)
{
$this->middleware('auth.employee:employee');
}
public function index(Request $request)
{
$users[] = Auth::user();
$users[] = Auth::guard()->user();
$users[] = Auth::guard('employee')->user();
dd($users);
return view('employees.home.index');
}
}
Auth::shouldUse(your_guard_name);
call this in your login function
Change the driver name in the config/auth.php as..
'employees' => [
'driver' => 'eloquent',
'model' => App\Models\UserEmployee::class,
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Models\Customer::class,
],
I have a Post model that has a many-many relationship with Tags.
Defined in Post model:
public function getTags(){
return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
->viaTable('post_tags', ['post_id' => 'id']);
}
But Post::tags is read-only. So when I try to set them in the Controller, I get an error:
Invalid Call – yii\base\InvalidCallException
Setting read-only property: app\models\Post::tags
The controller is using load to set all the properties:
public function actionCreate(){
$P = new Post();
if( Yii::$app->request->post() ){
$P->load(Yii::$app->request->post());
$P->save();
return $this->redirect('/posts');
}
return $this->render('create', ['model'=>$P]);
}
The input field in the view:
<?= $form->field($model, 'tags')->textInput(['value'=>$model->stringTags()]) ?>
Why is Post::tags read-only? And whats the proper way to set a model relationship?
Here tags
public function getTags(){
return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
->viaTable('post_tags', ['post_id' => 'id']);
}
is a relation name and returns the object and is not just a attribute or database column.
You cannot use it with textInput() like other attribute for eg email, first_name.
So you are given error of Setting read-only property.
In order to remove this error, you need to create new attrbute or property to model like below
class Post extends \yii\db\ActiveRecordsd
{
public $tg;
public function rules()
{
return [
// ...
['tg', 'string', 'required'],
];
}
// ...
In view file
<?= $form->field($model, 'tg')->textInput(['value'=>$model->stringTags()]) ?>
Setting read-only property: app\models\Post::tags because you need add in your model property $tags:
public $tags;
In most cases, setting a relation is not required. But if you need it:
php composer.phar require la-haute-societe/yii2-save-relations-behavior "*"
Model
class Post extends yii\db\ActiveRecord
{
public function behaviors()
{
return [
'saveRelations' => [
'class' => SaveRelationsBehavior::class,
'relations' => [
'author',
],
],
];
}
}
Now this code will not cause errors Setting read-only property =)
$post->author = Author::findOne(2);
In addition, module yii2-save-relations-behavior help save easier hasMany relations
I have an Ardent v3.3.0 model like this:
class Company extends Ardent
{
protected $fillable = [
'name',
'address'
];
public static $rules = [
'name' => 'required',
'address' => 'string'
];
public function workers()
{
return $this->belongsToMany('App\Worker')->withPivot('worker_type');
}
}
Another model that goes something like this:
class Worker extends Ardent
{
protected $fillable = [
'name',
];
public static $rules = [
'name' => 'required',
];
public function company()
{
return $this->belongsToMany('App\Company')->withPivot('worker_type');
}
}
In my controller I'm calling a save method like this:
$worker = New Worker;
$worker->name = "Jane Smith";
$company = Company::find($id);
$company->workers()->save($worker, ['worker_type' => 'contractor'];
According to Laravel's and Ardent's docs I'm correctly forming my relationships but Ardent throws an error: ErrorException in Ardent.php line 821: Invalid argument supplied for foreach()
What's causing this error? Is it a bug in my code or Ardent's?
Note: I'm using Ardent version 3.3.0, the issue disappears when I roll back to version 3.0.0
You haven't defined the rules for one or more of your models that extend Ardent.
class Whatever extends \LaravelArdent\Ardent\Ardent {
public static $rules = [];
}
Line 821 shows that we're looking for an array called $ruleset that we can't find.