How to use attach with two tables and two connect in laravel? - 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)
}

Related

How to modify a relationship?

My app has 2 main modules which are Foo and Bar. It also has 3 types of role: admin, manager & staff.
Each user is assigned to a supervisor, so that every supervisor will have some subordinates assigned to him/her.
For example, staff1 is supervised by manager1 whom is also supervised by admin1.
The current practice for this relationship is implemented in both modules. Therefore each supervisor is in charge for the subordinates in the matter of their Foo and Bar.
User.php
<?php
namespace App;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Str;
class User {
protected $fillable = ['name','email','password','supervisor_id'];
protected $appends = ['role'];
public function getRoleAttribute(){
return $this->roles[0];
}
public function getNameAttribute($value){
return Str::title($value);
}
public function parent(){
return $this->hasOne('App\UserStructure', 'user_id');
}
public function scopeSupervisor($query){
return $query->where('id', $this->supervisor_id)->first();
}
public function foo(){
return $this->hasMany(Foo::class, 'user_id', 'id');
}
public function bar(){
return $this->hasMany(Bar::class, 'user_id', 'id');
}
}
UserStructure.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserStructure extends Model{
protected $fillable = ['user_id', 'parent_id'];
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
}
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model{
protected $fillable = ['name'];
public function roles(){
return $this->belongsTo('App\User', 'role');
}
}
RoleAndPermission.php
<?php
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class RolesAndPermissionsSeeder extends Seeder{
public function run(){
$roles = ['admin','manager','staff'];
app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
foreach ($roles as $role) {
Role::updateOrCreate(['name' => $role]);
}
}
}
UserSeeder.php
<?php
use Illuminate\Database\Seeder;
use App\User;
use App\UserStructure;
class UserSeeder extends Seeder{
public function run(){
$items = [
['role'=> 'admin',
'name'=> 'admin',
'email'=> 'admin#myapp.com',
'password'=> 'password',
'supervisor_id'=> 1],
['role'=> 'manager',
'name'=> 'manager',
'email'=> 'manager#myapp.com',
'password'=> 'password',
'supervisor_id'=> 1],
['role'=> 'staff',
'name'=> 'staff',
'email'=> 'staff#myapp.com',
'password'=> 'password',
'supervisor_id'=> 2],
];
foreach($items as $data) {
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'supervisor_id' => $data['supervisor_id'],
]);
$user->assignRole($data['role']);
}
$userStructure = [
['parent_id'=> 0, 'user_id'=> 1],
['parent_id'=> 1, 'user_id'=> 2],
['parent_id'=> 2, 'user_id'=> 3]
];
UserStructure::insert($userStructure);
}
}
My question is, how do I modify this relationship accordingly so that any supervisor [admin/ manager] will be assigned to the subordinate [manager/ staff] of one module only?
(E.g:
In Foo module, staff1 is supervised by manager1.
While in Bar module, he will be supervised by manager2.)
As i understand, you can add one column to the Role model (like type), and then assign roles to users with a condition

How to use relationship inside another relationship of other model?

I want to use public function scheduleTime() to check sechudle_time inside newsLetterSentOn() of News Model.
If this can be done,please help me regarding this.Thank you.
This is News Model
<?php
namespace Modules\Newsletter\Entities;
use Brexis\LaravelWorkflow\Traits\WorkflowTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
/**
* This is for storing news
* Class News
* #package Modules\Newsletter\Entities
*/
class News extends Model {
use WorkflowTrait;
protected $table = 'news_info';
protected $fillable = [
'title', 'header', 'description', 'status', 'created_by', 'media_url', 'media_thumbnail', 'media_type'
];
public function newsLetterSentOn() {
return $this->belongsToMany(Newsletter::class,'news_newsletters','news_id','newsletter_id')
->whereHas('scheduleTime', function($q){
$q->where('schedule_time', '<', date("Y-m-d h:i:s", time()));
});
}
}
This is Newsletter Model
<?php
namespace Modules\Newsletter\Entities;
use Illuminate\Database\Eloquent\Model;
class Newsletter extends Model
{
protected $table = 'newsletters';
protected $hidden = ['pivot'];
protected $fillable = [];
public function scheduleTime()
{
return $this->belongsTo(ScheduleTime::class,'id','newsletter_id');
}
}
You can get nested relationship with dot notation like so:
$news = News::with(['newsLetterSentOn.scheduleTime' => function($q)
$q->where('schedule_time', '<', date("Y-m-d h:i:s", time()));
])->find($id);
Then you can access it through $news like normal.
$news->newsLetterSenton->scheduleTime;

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

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"
}
}

How to make dynamic query in laravel 5 with model and controller

i have Add query in codeigniter like this:
in controller:
$data=array(
'table'=>'tbl_activity_log',
'val'=>array(
'x'=>$x,
'y'=>$y,
'z'=>$z,
));
$log=$this->model->add_data($data);
And in model add_data function like this:
function add_data($data)
{
return $this->db->insert($data['table'],$this->security->xss_clean($data['val']));
}
But In Laravel 5 I have:
$name=$Request->input('name');
$lname=$Request->input('lname');
$myItems = array(
'first_name'=>$name,
'last_name'=>$lname
);
DB::table("tbl_user")->insert($myItems);
My question is, how can we make table field dynamic in Laravel and call that function through model.
Also, how can I call that function from model? Any help please. I want a dynamic query
You can write a helper function
//create a helper function
function addModelData($arrayData = [])
{
return \DB::table($arrayData['table'])->insert($arrayData['val']));
}
//in your controller or any place you like
$data=array(
'table'=>'tbl_activity_log',
'val'=>array(
'x'=>$x,
'y'=>$y,
'z'=>$z,
));
$log = addModelData($data);
You could create a model as described in official documentation:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'tbl_user';
// If your primary key is not 'id'
protected $primaryKey = 'model_id';
}
Now in your controller you can use this model:
namespace App\Http\Controller;
use App\User;
use Illuminate\Http\Request;
class MyController extends Controller {
public function myAction(Request $request){
$user = new User();
$user->last_name = $request->input('lname');
$user->first_name = $request->input('name');
$user->save();
}
}
You also could use mass assignment. But before you have to set the $fillable attribute in your model:
protected $fillable = ['first_name', 'last_name'];
Now you can use mass assignment in your controller:
$user = User::create([
'first_name' => $request->input('name'),
'last_name' => $request->input('lname')
]);
// alternatively:
$user = User::create($request->only(['name', 'lname']));

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist

When I try to save data from laravel form to a database table I am getting the following exception:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist (SQL: select count(*) as aggregate from store where name = samplename)
the table store exists but still I am getting the error
this is my contoller that is processing the form:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\storestore;
use App\Http\Requests\storeFormRequest;
class AddstoreController extends Controller
{
//
public function create()
{
//
}
public function store( storeFormRequest $request)
{
$store = new Store;
$store->name = Input::get('name');
$store->description = Input::get('description');
$store->store_vendor_id = Input::get('owner');
$store->contact_email = Input::get('contact_email');
$store->postal_address = Input::get('postal_address');
$store->city = Input::get('city');
$store->zip = Input::get('zip');
$store->phone = Input::get('phone');
$store->business_logo = Input::get('logo');
$store->save();
return \Redirect::route('add_store_success')
->with('message', 'Thanks for joining us!');
}
}
This is my Store model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
StoreRequest file:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\StoreController;
class StoreFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required|unique:dstore',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:dstore',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}
}
These are the get and post routes:
Route::get('/store_form', ['as' => 'add_store_form', 'uses' => 'StoreController#create']);
Route::post('/store_form',['as' => 'dstore', 'uses' => 'StoreController#store']);
Both routes are listed when I run php artisan route:list command
I have tried to goggle for solution but the one I landed on pointed out to missing tables as a course, but in my case the store table is existing but still I am getting the error.
Any help please!
Look at your Store model class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
As you see property $table is set to stores so I assume table name in your database is stores and not store.
You should probably change in your StoreFormRequest content or rules method to use in unique rule valid table name, for example:
public function rules()
{
return [
//
'name' => 'required|unique:stores',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:stores',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}

Resources