I wanna try to make test, member who logged in can create a job, this is my test code.
/** #test */
public function member_can_create_a_job(){
$member = factory('App\Models\M_member')->create();
$this->actingAs($member);
$job = factory('App\Models\M_lowker')->make();
$this->post('/lowker/tambah-lowker', $job->toArray())->assertRedirect('/lowker/tambah-lowker');
}
This is my App\Models\M_member
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class M_member extends Model{
protected $table = "member";
public $timestamps = false;
protected $fillable = ["nama", "email", "password", "alamat", "tgl_lahir", "remember_token"];
public function jobs()
{
return $this->hasMany('App\Models\M_lowker');
}
public function comments()
{
return $this->hasMany('App\Models\M_komentar');
}
}
When I run, I get error in cmd like
this.
1) Tests\Feature\JPSTest::member_can_create_a_job TypeError: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::actingAs() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\M_member given, called in I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php on line 35
I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication.php:16 I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php:35
ERRORS! Tests: 3, Assertions: 3, Errors: 1.
This error tells you that the model which you are using is not extending the Illuminate\Contracts\Auth\Authenticatable contract, which is necessary to use the actingAs method. If you have laravel's auth you can check the user model as an example of this . Which is something like:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
So, try extending your model to have this functionality.
or you can implement the Authenticatable contract on your model like this
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
You can add first() when you create user
$user = factory('App\User')->create()->first();
This problem solved with modify my M_member model like this.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
class M_member extends Model implements Authenticatable{
use AuthenticableTrait;
Related
I have 3 tables:
subdistrict (in database B)
users (in database A)
admin_area (in database A).
and now, i want to insert or display data for user with area. below is the code i have made:
Model User
<?php
namespace App\Models;
use App\Models\Marketplace\Subdistrict;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles, SoftDeletes;
public function areas()
{
return $this->belongsToMany(Subdistrict::class, 'admin_area', 'user_id', 'subdistrict_id');
}
}
Model Subdistrict
<?php
namespace App\Models\Marketplace;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subdistrict extends Model
{
use HasFactory;
protected $connection = 'marketplace';
protected $table = 'subdistrict';
public function users() {
return $this->belongsToMany(User::class, 'admin_area', 'user_id', 'subdistrict_id');
}
}
admin_area table:
user_id
subdistrict_id
If I try to get the areas from user_id = 1, I get an error like below
How to fix it? or How to make pivot table with different database in laravel 8?
Barring any design considerations, you can try by including the database name in front of the table. I'm assuming that the databases are in the same server.
Try alternating database_a or database_b (I'm not 100% clear on how the relationship was created).
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles, SoftDeletes;
public function areas()
{
return $this->belongsToMany(Subdistrict::class, 'database_a.admin_area', 'user_id', 'subdistrict_id');
}
}
need help laravel. I have 2 model in different folder
app\User
app\model\Role
there is no problem when i used at UsersController -> call app\User, or RolesController -> call app\model\Role
but, when i used both models on UsersController , the app\model\Role didnt work
==================== UsersController ======================
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use app\User;
use app\model\Role as Role;
use DataTables;
class UserController extends Controller
{
public function index(Request $request){
$data['title_page'] = 'User';
$data['roles'] = Role::all(); // this line show error
return view('admin/user', $data);
}
}
======================== app\model\Role ===================
namespace App\model;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
protected $fillable = ['id','name'];
protected $tables = 'roles';
public function users(){
return $this->belongsTo('App\User','role');
}
}
======================== app\User =======================
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = "users";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role', 'status'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function roles(){
return $this->hasOne('App\model\Role','id');
}
}
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Class 'app\model\Role' not found
Try with capital 'A' on 'App'. Some systems are case sensitive. So use App\Model\Role depending on your folder name for model. IE if your model folder is lower case, match it in the use statement.
Also, you don't need the as keyword here unless there are conflicts - you may be fine with just use App\Model\Role without the as Role.
One more item, make sure the Role class is actually in the model folder and that your namespace is at the top of the php file correctly referencing the App\Model namespace. So in your Role class make sure the caps match your use call -
<?php
namespace App\Model
I'm trying to force my application to use the write connection when running a select because of race conditions dealing with updating the data and refreshing it. I have confirmed that useWritePdo() function is being called, but I can tell it's not using the write connection because the race condition bug still exists. I don't know how to determine through var dumps whether the write connection is being used.
Here is the code I'm running, followed by the involved models. Note that forcing the write connection works if I call $portfolio->items($useWriteConn), but not $user->portfolios($useWriteConn)->with('items').
return $this->user->portfolios($useWriteConn)->with('items')->find($id);
Model User.php:
namespace App;
use App\Notifications\ResetPassword;
use App\Support\Auth\RetrievesUser;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
/**
* Class User
* #package App
* #property integer $subscription
* #property integer $id
*/
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, UserTrait, Notifiable, HasApiTokens, RetrievesUser
public function portfolios($useWriteConn = false)
{
return ($useWriteConn)
? $this->hasMany(UserPortfolio::class, 'user')->writeConn()
: $this->hasMany(UserPortfolio::class, 'user');
}
}
Model UserPortfolio.php
namespace App;
// use App\UserCustomViews;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserPortfolio extends Model
{
use SoftDeletes;
public function user()
{
return $this->belongsTo(User::class, 'user');
}
public function items($useWriteConn = false, $showClosed = true)
{
$items = $this->hasMany(UserPortfolioItem::class, 'portfolio');
if ($useWriteConn)
$items->writeConn();
if (!$showClosed)
$items->open();
return $items;
}
public function scopeWriteConn($query)
{
return $query->useWritePdo();
}
}
Model UserPortfolioItem.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;
class UserPortfolioItem extends Model
{
public function portfolio()
{
return $this->belongsTo(UserPortfolio::class, 'portfolio');
}
public function scopeWriteConn($query)
{
return $query->useWritePdo();
}
}
For anyone who comes across this later, I found the answer in another thread.
Eloquent pre-loading relationships against DB write connection
Model::onWriteConnection()->with(['relationship'=>function($query){
$query->useWritePdo();
}])->find($id)
I have written code for registration and login using JWT authentication. In this code registration function works fine but login function doesn't works. Login function prompts an error as Class 'Illuminate\Foundation\Auth\User' not found
My user model is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'users';
public $timestamps = false;
protected $primaryKey = 'user_name';
protected $fillable = ['user_name','password'];
}
My UserController is
class UsersController extends Controller
{
public function login()
{
$credentials = request()->only('user_name','password');
try{
$token = JWTAuth::attempt($credentials);
if($token){
return response()->json(['error'=>'invalid_credentials'],401);
}
}
catch(JWTException $e){
return response()->json(['error'=>'something went wrong'],500);
}
return response()->json(['token'=>$token],200);
}
public function register()
{
$user_name = request()->user_name;
$password = request()->password;
$user = User::create([
'user_name'=>$user_name,
'password'=>bcrypt($password)
]);
$token = JWTAuth::fromUser($user);
return response()->json(['token'=>$token],200);
}
}
The login function shows the error as
Class 'Illuminate\Foundation\Auth\User' not found
In your controller I guess you forgot to use your model "User" add it below the namespace declaration, Or it's a conflict with Illuminate\Foundation\Auth\User
use\App\User;
And you must run the following:
composer update
composer dump-autoload
The problem exists with my user model and I solved it
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{use Authenticatable, CanResetPassword;
//
protected $table = 'users';
public $timestamps = false;
protected $primaryKey = 'user_name';
protected $fillable = ['user_name','c_name','accessibility_level','password','role','contact_number','address'];
}
I'm trying to build my first Laravel application by following a few guides on the internet and I'm feeling I'm missing something obvious. Here is the code.
Error
BadMethodCallException in Builder.php line 2450: Call to undefined
method Illuminate\Database\Query\Builder::addresses()
User-Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Sentinel;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'email', 'password',
];
protected $hidden = [
'password',
'remember_token'
];
public function addresses()
{
return $this->hasMany('App\CustomerAddress');
}
}
CustomerAddress-model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerAddress extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
CustomerAddress-controller
<?php
namespace App\Http\Controllers;
use App\CustomerAddress;
use Illuminate\Http\Request;
class CustomerAddressController extends Controller
{
public function create(Request $request)
{
$address = new CustomerAddress();
$address->address = $request['address'];
$request->user()->addresses()->save($address);
}
}
Error appears after this piece of code:
$request->user()->addresses()->save($address);
Any ideas? Thanks and cheers
In .config/cartalyst.sentinel.php, change 'model' => 'Cartalyst\Sentinel\Users\EloquentUser' to 'model' => 'App\User' to use your user model with the addresses relation defined
In ./app/User change User extends Authenticatable to User extends \Cartalyst\Sentinel\Users\EloquentUser to extend sentinel's user to your app's User model
Finally, your controller code should now be
`$address = new CustomerAddress();
$address->address = $request->input('address');
$request->user()->addresses()->save($address);`
and everything should be peachy