Laravel Call to undefined method Illuminate\Database\Eloquent\Builder::privilege() - laravel

I would like to display privileges('name') instead of idPrivilege in the user collection. I have tried to add a relationship and use it in an Eloquent call but I'm getting an error.
User model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
protected $primaryKey = 'idUser';
protected $fillable = [
'name', 'email',
];
protected $hidden = [
'password', 'updated_at',
];
public function privilege()
{
return $this->hasOne(Privilege::class, 'idPrivilege', 'idPrivilege');
}
}
Privilege model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Privilege extends Model
{
protected $table = 'privileges';
protected $primaryKey = 'idPrivilege';
protected $fillable = [
'name',
];
protected $hidden = [
'updated_at',
];
public function user()
{
return $this->belongsTo(User::class, 'idPrivilege', 'idPrivilege');
}
}
UserController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function relationTest()
{
return User::where('idUser', 1)->privilege()->get();
}
}
I'm getting the below error when I use with('privilege') to my User collection is added privilege collection.
Call to undefined method Illuminate\Database\Eloquent\Builder::privilege().

where returns a Builder instance on which a privilege method does not exist, so you can simply use it as such:
return User::find(1)->privilege()->get();;
-- EDIT
User::find(1)->with(['privilege' => function($query) {
$query->select('name');
}])->get();

I can achieve it by using resource:
$user = User::where('idUser', 1)->with('privilege')->first();
return UserResource::make($user);
Inside UserResource:
public function toArray($request)
{
return [
'idUser' => $this->idUser,
'name' => $this->name,
'email' => $this->email,
'privilege' => $this->privilege['name'],
'createdAt' => $this->created_at,
];
}
but was hoping there is simplier method of getting that.
output:
{
"data": {
"idUser": 1,
"name": "Martin",
"email": "martin#martin.martin",
"privilege": "user",
"createdAt": "2019-05-05T01:11:43.000000Z"
}
}

Related

How to use attach with two tables and two connect in laravel?

I use Laravel 8x, and i have two connections:
In .env :
DB_HOST=xx.xx.xx.xx
DB_PORT=xxxx
DB_DATABASE=product
DB_USERNAME=product_sp
DB_PASSWORD=xxxxxxxxx
DB_HOST_PROMOTION=xx.xx.xx.xx
DB_PORT_PROMOTION=xxx
DB_DATABASE_PROMOTION=product_sand
DB_USERNAME_PROMOTION=product_sp
DB_PASSWORD_PROMOTION=xxxxxxxxxxx
In model:
Product.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notification;
class Product extends Model
{
use HasFactory;
protected $table = 'product';
protected $keyType = 'string';
public $incrementing = false;
public function discount()
{
return $this->belongsToMany(Discount::class, 'product_discount', 'productId', 'discountId')->withPivot(['id','status', 'quantity', 'createdAt', 'updatedAt', 'createdBy','updatedBy']);
}
}
discount.php :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notification;
class Discount extends Model
{
use HasFactory;
protected $table = 'discount';
protected $connection = 'promotion';
protected $keyType = 'string';
public $incrementing = false;
}
The product_discount table is an intermediate table of discount and product.
In the controller, I use attach
public function store(Request $request)
{
$req = $request->all();
$product = new Product($req);
$extraFieldPivot = [
'id' => (string) Str::uuid(),
'status' => 1,
'quantity' => 1,
'createdAt' => now(),
'updatedAt' => now(),
];
$product->discount()->attach($req['idDiscount'], $extraFieldPivot)
}
But when I check the data. The result has not been saved to the database. So where did I go wrong, please advise me. Thank you very much.
i think your intermediate table needs to be changed like productId to product_id and discountId to discount_id.
and change your relationship according to your change in table
If your model relationship is correct change your store function to
$public function store(Request $request)
{
$req = $request->all();
$product = Product::create($req);
$extraFieldPivot = [
'id' => (string) Str::uuid(),
'status' => 1,
'quantity' => 1,
'createdAt' => now(),
'updatedAt' => now(),
];
$product->discount()->attach($product, $extraFieldPivot)
}

incorrect table name inserting into using Laravel Excel to Collection

I'm attemptng to insert relational data using the Laravel Excel concern ToCollection
use Maatwebsite\Excel\Concerns\ToCollection;
however the query is attempting to insert into the table objective_years and not objective_year
ObjectivesImport.php
namespace App\Imports;
use App\Models\Objective;
use App\Models\ObjectiveYear;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
class ObjectivesImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
$objectiveDetail = Objective::create([
'description' => $row[0],
'guidance' => $row[1],
'team_id' => $row[2],
'subject_id' => $row[3],
]);
$yearDetail = ObjectiveYear::create([
'objective_id' => $row[4],
'year_id' => $row[5],
]);
}
}
}
I have two models with a many to many relatinship pivot.
Objective
class Objective extends Model
{
use HasFactory;
protected $fillable = [
'description', 'guidance','subject_id','team_id'
];
public function years ()
{
return $this->belongsToMany('App\Models\Year');
}
}
Year
class Year extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
public function objectives()
{
return $this->belongsToMany('App\Models\Objective')->withTimestamps();
}
}
ObjectiveYear
class ObjectiveYear extends Model
{
use HasFactory;
protected $fillable = [
'objective_id', 'year_id'
];
}
Controller
class ImportController extends Controller
{
public function getImport()
{
return view('import');
}
public function import()
{
Excel::import(new ObjectivesImport, request()->file('csv_file'));
return redirect('/')->with('success', 'All good!');
}
}

Method Illuminate\\Database\\Eloquent\\Collection::createToken does not exist

I am using laravel passport in py project and I want to create a token in every request for making it secure, but it not work now and I really became confused that what is the problem with my code, please help me.
here is my Model
use App\Models\Post;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\Models\Media;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable implements HasMedia
{
use HasApiTokens, Notifiable;
use HasMediaTrait;
public function registerMediaConversions(Media $media = null)
{
$this->addMediaConversion('thumb')
->crop('crop-center', 50, 50);
$this->addMediaConversion('list')
->fit('crop', 312, 312);
$this->addMediaConversion('big')
->fit('fill', 1248, 1248);
}
protected $fillable = [
'name', 'email', 'password', "role"
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
public function posts()
{
return $this->hasMany(Post::class, 'post_author');
}
}
here is my controller
{
$data = \App\User::all();
$accessToken = $data->createToken('Token')->accessToken;
return response(['usersData' => $data]);
}
I solved my problem with bellow code:)
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);

How do I interact with the four Eloquent models correctly?

The project consists of four related tables:
orders (id, status, client_email, partner_id)
order_products (id, order_id, product_id, quantity, price)
partners (id, email, name)
prods (id, name, price, vendor_id)
creating 4 models:
<?php
//App\Order.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'id', 'status', 'client_email', 'partner_id',
];
public function partner()
{
return $this->belongsTo('App\Partner');
}
public function order_product()
{
//belongsToMany - server error
return $this->belongsTo('App\Prod', 'order_products');
}
public function prod()
{
return $this->belongsTo('App\Prod');
}
}
<?php
//App\Partner.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
protected $fillable = ['id', 'email', 'name'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Order_product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order_product extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Prod.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Prod extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function order()
{
return $this->belongsToMany('App\Order', 'order_products');
}
}
creating Order Resources:
<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Order extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'status' => $this->status,
'client_email' => $this->client_email,
'partner_id' => $this->partner_id,
'partner_name' => $this->partner->name,
//return server error
'product_id' => Prod::collection($this->order_product),
'name' => $this->prod->name,
];
}
}
creating Prod Resource:
<?php
//App/Http/Resources\Prode.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Prod extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}
And return from Order Controller:
<?php
//App\Http\Controllers\Api\OrderController.php
namespace App\Http\Controllers\Api;
use App\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\Order as OrderResource;
class OrderController extends Controller
{
public function index()
{
$orders = Order::with(['partner', 'order_product', 'prod'])->get();
return OrderResource::collection($orders);
}
}
How do I get the product name in the order?
Order_product seems like a name for a pivot table. This isn't necessary in laravel because the frameworks assumes the table structure by default. The recommended approach is creating the following models:
Order
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'id', 'status', 'client_email', 'partner_id',
];
public function partner()
{
return $this->belongsTo('App\Partner');
}
public function products()
{
return $this->belongsToMany('App\Product', 'order_products');
}
public function prod()
{
return $this->belongsTo('App\Prod');
}
}
Product (Prod)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'prod';
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function orders()
{
return $this->belongsToMany('App\Order', 'order_products');
}
}
and with the following resources:
OrderResource
<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class OrderResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'status' => $this->status,
'partner_id' => $this->partner_id,
'partner_name' => $this->partner->name,
'products' => ProductResource::collection($this->products),
'name' => $this->prod->name,
];
}
}
ProductResource
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}
more details over many to many relations can be found in the docs.

Cannot declare class App\Models\User, because the name is already in use, when trying to login?

I'm trying to make a simple login just for the moment and when I try to login I get this error
Cannot declare class App\Models\User, because the name is already in use
In my User Model, this is the model
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'username', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
The error says on this line
class User extends Authenticatable
This is my submit method on my Login.vue
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/login', {
username: this.form.username,
password: this.form.password,
}).then(() => this.loading = false)
} else {
return false;
}
});
},
What am I doing wrong?

Resources