How can i fetch another table data in different table column? - php

Firstly i have given all three table structure.
actions table:
roles table:
permissions table:
Here how can i get action_id in permissions table from actions table?
and how can i get role_id in permissions table from roles table? Please tell me the easy way to do , i am beginner in Laravel.
Action Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Action extends Model
{
//
protected $table = "actions";
//public $fillable = []
public function role(){
return $this->belongsTo('App\Action');
}
public function permission(){
return $this->belongsTo('App\Action');
}
}
Permission Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Permission extends Model
{
//
protected $table ="permissions";
public function actionGet(){
return $this->hasOne('App/Permission');
}
}

update permission_table a join action_table b on a.id = b.id join roles_table c
on a.id = c.id
set a.action_id = b.id,
a.role_id = c.id;
This will update action_id in permission table with id from action table
also, role_id in permission table with id from role table.
I assume this is what you want.

I have found a way to do this work.I am using for this Query Builder to insert actions table id in permissions table action_id column.
For this, in RoleController:
public function store(Request $request)
{
//
$role = [];
$role['role'] = $request->input('role');
$data= Role::create($role);
$id= $data->id;
DB::table('permissions')->insert([
'role_id' => $id
]);
return redirect(route('allRole'));
}
And ActionController:
public function store(Request $request)
{
//
$action= [];
$action['action'] = $request->input('action');
$data= Action::create($action);
$id= $data->id;
DB::table('permissions')->insert([
'action_id' => $id
]);
return redirect(route('allAction'));
}
Before do this add use DB; in your header of each controller.
Hope this will help for someone.

Related

Laravel attach data to pivot table

So i am working on a laravel project with multiple table's and pivot table's but i cant attach data to a specific pivot table because it wont accept the name.
as a user i want to be able to download files from the 'file' crud. That works. but after i downloaded i want to be able to see who downloaded what file as an admin, this does not work
the query i get is:INSERT INTO file_user (file_id, user_id) VALUES (7, 2)
i basically want to change the: file_user to download. but i have no idea how to do that without making a full query
table 'file'
id
-name
-file (document)
table 'user'
-id
-name
-username
-role
pivot table 'download'
-id
-file_id
-user_id
user model:
public function role(){
return $this->belongsTo(Role::class,'role_id');
}
public function file(){
return $this->belongsToMany(File::class);
}
file model:
public function user(){
return $this->belongsToMany(User::class);
}
protected $table = 'file';
download model (pivot)
protected $table = 'download';
protected $fillable = [
'file_id',
'user_id',
];
public function file() {
return $this->belongsTo('file');
}
public function user() {
return $this->belongsTo('users');
}
controller:
public function download(Request $request, int $fileId)
{
$id = Auth::user();
$fullfile = File::find($fileId);
$downloadfile = File::find($fullfile, ['file'])->pluck('file')->last();
// return response()->download($downloadfile);
dd($fullfile->user()->attach($id));
return back();
}
In this case you have to pass the table name too.
public function file(){
return $this->belongsToMany(File::class, 'download');
}
public function user(){
return $this->belongsToMany(User::class, 'download');
}
I use a pivtot table for my application to simply be able to link multiple users to a task. However I do not use a model for my pivot table.. I don't think it is needed, you just need to migration table,
{
Schema::create('task_user', function (Blueprint $table) {
$table->foreignId('task_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
});
}
This is what I have.. If you did this it will simply save a user and your file when you attach a user.. if this function has the download too you could just check for the users on that file(they will have downloaded it)
you could go
$file->users()
And this would get your downloads (or make a scope for this since it will be easier to read)
I hope this helps!
to work with pivot table in laravel, you most likely choose between 2 things: the pivot method and making a Pivot Model:
files[ id, name]
users[ id, name]
downloads[ id, file_id, user_id, download_at]
First solution: pivot method:
+File Model (i will only put the relationship method here):
public function users()
{
return $this->belongsToMany(User::class, 'downloads') //'downloads' is the table name, default is 'user_file'
->as('download'); //optional, this is how to access the table in code, default is 'pivot' $user->files->pivot, now $user->files->download
}
+User Model:
public function files()
{
return $this->belongsToMany(File::class, 'downloads')->as('download');
}
+How to use:
//get user with id '1' and all of the files that he downloaded:
$user = User::with('files')->find(1);
$all_of_the_files_he_downloaded = $user->files;
//get file with id '2' and all the users that downloaded this file
$file = File::with('users')->find(2);
$all_users_that_downloaded_the_file = $file->users
//get the download time of every file that John Doe downloaded
$user = User::with('files')->where('name', 'John Doe')->get();
foreach($user->files as $file)
{
echo $file->download->downloadAt; //if you didn't use the ->as('download'): $file->pivot->downloadAt
}
//get the download time of every user that downloaded the file with name 'Rick Roll'
$file = File::with('users')->where('name', 'Rick Roll')->get();
foreach($file->users as $user)
{
echo $user->download->downloadAt;
}
Second solution: pivot Model
+Download Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Progress extends Pivot
{
protected $table = 'downloads'; //here we need to specify a table because we didnt follow convention, aka. Download instead of UserFile
public $incrementing = true; //specify auto-increment id
}
+User Model:
public function files()
{
return $this->belongsToMany(File::class)->using(Download::class);
}
+File Model:
public function users()
{
return $this->belongsToMany(User::class)->using(Download::class);
}

laravel and pivot table

I have 3 tables
Game(id, name), GameCategory(game_id, category_id), Category(id, title).
Partial code of classes:
class Game extends \Illuminate\Database\Eloquent\Model
{
protected $fillable = [
'name',
'title'
];
public function categories()
{
return $this->hasMany('VanguardLTE\GameCategory', 'game_id');
}
}
class Category extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'title'
];
public function games()
{
return $this->hasMany('VanguardLTE\GameCategory', 'category_id');
}
}
class GameCategory extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'game_id',
'category_id'
];
public function category()
{
return $this->belongsTo('VanguardLTE\Category');
}
public function game()
{
return $this->belongsTo('VanguardLTE\Game');
}
}
I need to select category titles for selected $game
This code give me only category_id.
$g_categories = $game->categories->pluck('category_id')->toArray();
This code not working:
$g_categories = $game->categories->category->pluck('title')->toArray();
As You mentioned to do
$g_categories = $game->categories->pluck('category_id')->toArray();
error_log('game_id'.$game->id.' category_ids:'.implode(",", $g_categories));
$g_titles = $game->categories->pluck('title')->toArray();
error_log('game_id'.$game->id.' category_titles:'.implode(",", $g_titles));
This will result with log like this:
game_id1907 category_ids:39,48
game_id1907 category_titles:,
From database side we see that data(title) is filled:
select g.id, g.name, g.title, c.id, c.title
from w_games g
join w_game_categories gc ON gc.game_id = g.id
join w_categories c ON c.id = gc.category_id
where g.id = 1907;
id
name
title
id
title
1907
OceanRulerSW
Ocean Ruler
39
Skywind
1907
OceanRulerSW
Ocean Ruler
48
Fish
Title in game is not necessary in this case but I added it here because have the same column name like title in categories.
You are accessing undefined relation .It should be
$g_categories = $game->categories->pluck('title')->toArray();
This line of code is incorrect and should be as follow:
$g_categories = $game->categories()->pluck('title')->toArray();
you did not add parentheses for categories.
The best solution is to use laravel way:
public function categories()
{
return $this->belongsToMany('VanguardLTE\Category');
}
public function games()
{
return $this->belongsToMany('VanguardLTE\Game');
}
In this way you should name your table as
category_game
and no need to define model for the intermediate table and you can simply access it through
$game->categories->pluck('title')->toArray();
in case you have any data in the pivot table just add ->withPivot('column_name') to your relationship
Refer to Laravel documentation for details

Trying to fill the intermediate table using attach() but getting "Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::attach()"

I have tables called users, places and user_place. users has a column called id that contains the id of the user and places has a column called place_id as well. The user_place table has 2 columns called user_id and place_id and I'm trying to automatically populate them with the corresponding ids. I read I have to use attach() function after setting up the relationships which I believe I have done but I might be wrong. Here they are:
class PlaceController extends Controller
{
public function likePlace(Request $request){
$placeId = $request['placeId'];
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
$place = new Place();
$place->place_id = $placeId;
$place->save();
$user->places()->attach($place);
}
}
User model:
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places(){
return $this->hasMany('App\Place');
}
}
Place mode:
class Place extends Model
{
public function user(){
return $this->belongsToMany('App\User');
}
}
In a Many to Many relationship, you should define both relationships like the following:
User.php
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places()
{
return $this->belongsToMany('App\Place', 'user_place', 'user_id', 'place_id');
} // ^^^^^^^^^^^^
}
Note: Given that your intermetiate table name doesn't follow the naming convention we specified so Laravel knows where table to look up.
Place.php
Notice that you mentioned that the primmary key of your Place model is place_id, and this also scapes from the Laravel convention you should specify it:
protected $primaryKey = 'place_id'; // <----
class Place extends Model
{
public function user()
{
return $this->belongsToMany('App\User', 'user_place', 'place_id', 'user_id');
}
}
So now in your controller:
class PlaceController extends Controller
{
public function likePlace(Request $request)
{
$placeId = $request['placeId'];
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
$place = new Place();
$place->place_id = $placeId;
$place->save();
$user->places()->attach($place);
}
}
Side note
As I side note, you could save a couple of line replacing some sentences with their equivalent:
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
Using the find() method, this is equal to:
$user = User::find($request['userId']);
Then, you could create your related object using the static method create of an Eloquent model so this:
$placeId = $request['placeId'];
$place = new Place();
$place->place_id = $placeId;
$place->save();
Is equal to this:
$place = Place::create(['place_id' => $request['placeId']]);
Then your controller will be reduced to this:
class PlaceController extends Controller
{
public function likePlace(Request $request)
{
$user = User::find($request['userId']);
$place = Place::create(['place_id' => $request['placeId']]);
$user->places()->attach($place);
}
}

How to insert pivot table in case of many to many relation? (Laravel 5.3)

My form to add data is like this :
When klik save, It will call controller
My controller is like this :
public function store(Request $request)
{
$param = $request->only('account_name','account_number','bank_id','branch');
$result = $this->user_service->addUserBank($param);
if($result)
$status='success';
else
$status = 'failed';
return redirect('member/profile/setting/account')->with('status',$status);
}
My service is like this :
public function addUserBank($param)
{
$instance = User::where('id', '=', auth()->user()->id)->first();
$param['user_id'] = auth()->user()->id;
$param['status'] = 0;
$instance->banks()->attach([
'status' => $param['status'],
'account_name' => $param['account_name'],
'account_number' => $param['account_number'],
'branch' => $param['branch']
]);
return $result;
}
My model user is like this :
<?php
namespace App;
use App\Models\MasterData;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, FormAccessible;
protected $fillable = [
'name', 'email', 'password', 'api_token','birth_date','mobile_number','gender','full_name'
];
protected $hidden = [
'password', 'remember_token',
];
public function banks()
{
return $this->belongsToMany(MasterData::class, 'users_banks', 'user_id', 'bank_id') ->withPivot('status','account_name','account_number','branch')->withTimestamps();
}
}
So I have 3 table : users table, users_banks table (pivot table), and master_datas table
List of the names of the banks located in the master_datas table with type bank
Users table have field id, name, email, password etc => See model user
Master_datas table have field id (this is bank id), name (this is bank name), type (there exist type of bank, order status etc. So, get type = bank)
Users_banks table have field id, user_id, bank_id, status, account_name, account_number, branch
When run, it does not successfully insert into the pivot table (table users_banks).
It looks like my way to insert into the pivot table, not true.
Can you help me?
Additional
Table Master_datas is like this :
The problem is that you are not passing bank_id in your addUserBank() method. you can do it as:
public function addUserBank($param)
{
$param['status'] = 0;
auth()->user()
->banks()
->attach($param['bank_id'], array_only($param, ['status', 'account_name', 'account_number', 'branch']);
return true;
}
Note: You don't need to set user_id explicitly here as Laravel will automatically do it for you.
Docs
Create UserBank model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserBank extends model
{
protected $table = 'user_banks';
protected $fillable = ['user_id','bank_id'];
}
And then populate the table from controller:
public function store(Request $request)
{
$param = $request->only('account_name','account_number','bank_id','branch');
$result = $this->user_service->addUserBank($param);
if($result)
{
$pivot=new UserBank();
$pivot->user_id=auth()->user()->id;
$pivot->bank_id=$request->bank_id;
if($pivot->save())
{
$status='success';
}
}
else
{
$status = 'failed';
}
return redirect('member/profile/setting/account')->with('status',$status);
}

cakePHP find("list") returns empty array

I am trying to make a drop down list of users by using the foreign key [UserID].
In the controller, I have find("list"). When I debug $this->Order->SalesAgent in the controller, it prints the User Object. However, in the view page, when I debug
the result of $this->Order->SalesAgent->find("list"), shows and empty array.
Heres the Controller:
public function edit_sales_agent ($id=null) {
debug($this->Order->SalesAgent);
$this->set("users",$this->Order->SalesAgent->find("list"));
debug($this->users);
}
and heres the View:
debug($users);
echo $this->Form->create("Order");
echo $this->Form->input("UserID");
$users is the result of find("list")
Could anyone help me out?
Thanks!
Association:
class Order extends AppModel{
public $useTable = 'CustomerOrder';
public $primaryKey = 'OrderID';
**public $belongsTo = array(
"SalesAgent"=>array(
"className"=>"User",
"foreignKey"=>"UserID"**
),
Sales Agent Model:
<?php
class User extends AppModel{
public $useTable = 'UserAccount';
public $primaryKey = 'UserID';
public $order = array(
"User.LastName"=>"asc",
"User.FirstName"=>"asc"
);
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['full_name'] = sprintf("(%s.FirstName+' '+%s.LastName)", $this->alias, $this->alias);
}
public function login($data){
return $this->find("first",array("conditions"=>$data['User']));
}
}
UPDATE:
Alright, so I figured out what the problem is but I dont know how to fix it.
When I type find(list), this is the query it runs:
SELECT [SalesAgent].[UserID] AS [SalesAgent__0],
[SalesAgent].[UserID] AS [SalesAgent__1] FROM [UserAccount] AS
[SalesAgent] WHERE 1 = 1 ORDER BY [User].[LastName] asc,
[User].[FirstName] asc
THis is the error it proposes:
SQL Error: The column prefix 'User' does not match with a table name
or alias name used in the query. [APP/Model/Datasource/Mssql.php, line
749]
The SalesAgent uses class User, which uses table UserAccount
I figured it out.
The problem was the query would run:
SELECT [SalesAgent].[UserID] AS [SalesAgent__0], [SalesAgent].[UserID]
AS [SalesAgent__1] FROM [UserAccount] AS [SalesAgent] WHERE 1 = 1
ORDER BY [User].[LastName] asc, [User].[FirstName] asc
where it would order by [User].LastName and [User].[FirstName].
User doesnt match the table name OR alias name, so I had to specify the order in cake.
array(
"fields"=>array("SalesAgent.username"),
' "order"=>["SalesAgent.UserID ASC"]
)
First try to configure your model association.
What is belong to what and the by running this
public function edit_sales_agent ($id=null) {
$users = $this->Order->SalesAgent->find("list");
$this->set("users",$users);
}
view try this
echo $this->Form->input("user_id");
You should have list of users.

Categories