Store foreign key value in laravel - laravel

In Migration Table:
Schema::create('passws', function (Blueprint $table) {
$table->increments('id');
$table->integer('regist_id')->unsigned()->nullable();
$table->foreign('regist_id')->references('id')->on('regists');
$table->string('age');
$table->timestamps();
});
}
Regist Model - Mass Assignment Defined.
public function pass(){
return $this->hasOne('App\Passw');
}
In Controller
$name = $request->name;
$task = Regist::whereName($name)->get();
foreach ($task as $tasks){
$passw1->regist_id = $tasks->id;
}
$passw1->age = $request->age;
$regist = new Regist();
$regist->pass()->save($passw1);
When i store data, only age is getting stored but regist_id stored as null, (no error message or nothing). Here i'm sure controller shows "regist_id" => 1 and "age" => 25 when i use dd($passw1); regist_id is only not getting stores in DB table.
Where am i doing an error??

Try this
$name = $request->name;
$regist = Regist::whereName($name)->first(); //it will give you a Regist model
$regist->pass()->create([
'age' => $request->age
]);
If you have more than one Regist for $name then try this
$regists = Regist::whereName($name)->get(); //it will give you a collection of Regist model
foreach ($regists as $regist){
$regist->pass()->create([
'age' => $request->age
]);
}
Check document here https://laravel.com/docs/5.6/eloquent-relationships#the-create-method

Related

laravel api resources autoincrement

how to laravel API resources add property in Row collection auto increment for row by row
"id" => (int)$this->id,
"fullname" => $this->fullname,
"city" => $city ? $city->name : 'نا مشخص',
"avatar" => ($this->avatar()->first()) ? img($this->avatar()->first()->path, '124x124') : '',
"count" => (int)$this->user_referral_count,
"rate" => autoincrement
if you set a field in your migration as increments it will be automatically incremented.
like bellow:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
...
...
...
});
}
and after that, when you create a new instance of User model. it's id will increase itself.
create new user like this:
$user = new User;
$user->name = 'hossein';
$user->email= '#hossein#k.t';
...
...
$user->save();

How to catch 1 colomn (id) on table in edit form

I have 1 table data . and I have function edit on this table . in this edit form I have select dropdown to show pluck from database .
I have 3 table . this name is aduan, ipsrs , teknisi
struckture aduan table
id
user_id
ipsrs_id
teknisi_id
aduan
etc.....
ipsrs table
id
nama_bagian
etc....
teknisi table
id
ipsrs_id
nama_teknisi
etc...
This is my controller :
public function index(Request $request)
{
$ipsrs = DB::table('ipsrs')->pluck('nama_bagian','id');
$belum_kerjakan = Aduan::with('users')->where('status','Belum Dikerjakan')->get();
$teknisi = Teknisi::where('ipsrs_id' , 1)->pluck('nama_teknisi', 'id');
$dalam_proses = Aduan::with('users')->where('status','Sedang Dikerjakan')->get();
$selesai = Aduan::with('users')->where('status','Selesai')->get();
return view('admin.admin_dashboard',[
'belum_dikerjakan' => $belum_kerjakan,
'dalam_proses' => $dalam_proses,
'selesai' => $selesai,
'ipsrs' => $ipsrs,
'teknisi' => $teknisi,
]);
}
Example this variable $belum_dikerjakan is showing table data and I have fucntion edit on this table ( in modal) .
But this I don't know how to catch data (ipsrs_id) to set where clause in the pluck . I want to change 1 to ipsrs_id form table , but how ?
If I understood the problem then here is the answer
pull only the ids from ipsrs table and pass to Teknisi table whereIn method
$ipsrsIds = DB::table('ipsrs')->pluck('id')->toArray();
$teknisi = Teknisi::whereIn('ipsrs_id' , $ipsrsIds)->pluck('nama_teknisi', 'id');
public function edit($id)
{
$category =Category::findOfFail($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

Query lastest Relationship, When Account was Created

I have two tables: Account and Transaction.
These tables relate to each other, by Account hasOne Transaction.
i want to show data in Transaction page, once Account was created.
My Account Model
public function transactions()
{
return $this->hasOne(\App\Transaction::class)->latest();
}
My Transaction Model
public function account()
{
return $this->belongsTo(\App\Account::class);
}
And my TransactionController
(I tried to implement code like below, but still no luck):
public function index()
{
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')->first();
}]);
return response()->json(['transactions' => $transactions]);
}
Any Help? Thanks.....
QueryBuilder chains need either a get() or a first() or something of that nature at the end to execute the query, right now the variable you're passing to the view is the unexecuted query builder. Try this
$transactions = Transaction::with(['account' => function($query) {
$query->orderBy('id', 'desc')
}])->get();
Although, as TimLewis pointed out in the comments, if the relationship between transactions and accounts is one to one then there's no need to do any ordering of the account so it can just be this
$transactions = Transaction::with('account')->get();
Oooopppp i found what i want....
In my AccountController
public function store(Request $request)
{
$validateData = $request->validate([
'name' => 'required',
'code' => 'required',
]);
$account = new Account();
$account->user_id = auth()->user()->id;
$account->code = $request->code;
$account->name = $request->name;
$account->description = $request->description;
$account->balance = $request->balance;
$account->save();
$transaction = new \App\Transaction();
$transaction->credit = $request->balance;
$account->transaction()->save($transaction);
return response()->json(['created' => true]);
}
i have to save Transaction Relationship with Account.

Reduce stock number in laravel

How can I reduce the number of stock in laravel?
In my products table i have stock column where i set numbers of item i have and i want to reduce it in 2 conditions:
1- when is added to order table (not when the product is in user cart)
2- when the order status is not cancelled (if order status become cancelled stocks increase back)
PS: currently I have no code for this matter that's why i didn't share
any code, I'm seeking for idea of how done it. Base on that i will
make functions and share here to complete it.
JSON of Order
"[{\"id\":29,\"name\":\"effewf\",\"price\":24524,\"quantity\‌​":1,\"attributes\":[‌​{\"attr\":{\"label\"‌​:\"Gray\",\"price\":‌​\"7000.00\"}}],\"con‌​ditions\":[]},{\"id\‌​":27,\"name\":\"new product\",\"price\":7246,\"quantity\":2,\"attributes\":[],\"‌​conditions\":[]}]"
UPDATE
base on #btl answer I added code below in my order model:
protected static function boot()
{
parent::boot();
$productIdsAndQuantities = $this->products->map(function ($product) {
return [$product->id => $product->quantity];
});
static::updating(function (Order $order) {
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
I think this code needs fix in $productIdsAndQuantities and $product->update(['stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)]); parts before i can use it.
currently i get error below when i try to add my cart detail to orders table
Using $this when not in object context
UPDATE 2
I changed my code to:
protected static function boot()
{
parent::boot();
static::updating(function (Order $order) {
$productIdsAndQuantities = $order->product_name->map(function ($product) {
return [$product->id => $product->quantity];
});
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id'));
if ($oldStatus->title !== 'Cancelled' && $order->orderstatus->title === 'Cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update([
'stock' => $stock + $product->order->getAttribute($productIdsAndQuantities)
]);
});
}
});
}
now my order will be placed but nothing changes on stock column.
any idea?
Your tables look like,
Product
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
......
$table->integer('stock');
$table->timestamps();
});
Stock
Schema::create('stocks', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned();
$table->integer('order_id')->unsigned();
$table->enum('fall_rise',[-1,1]);
$table->timestamps();
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('order_id')->references('id')->on('orders');
});
orders
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
.....
.....
$table->timestamps();
});
Now, add a sample product with stock value 10 like
$product = new Product();
$product->name = "abc";
......
$product->stock = 10;
$product->save();
Now, when abc is ordered, add details in order table. Now, stock value to be decreased then update value of stock column in product by 10-1 = 9, add record in stocks table like
Sample values,
product_id = 1;
order_id = 1;
....
fall_rise = -1;
In this way, when 10 stocks of the product are ordered then stock column becomes zero and hence product becomes unavailable. If you want to fetch only available products then use query like,
$available_products = Product::where('stock', '>', 0)->get();
I hope you will understand.
Register model events to handle updates on orders.
In your Order model:
protected static function boot()
{
parent::boot();
static::updating(function (Order $order) {
// restock if cancelled
$oldStatus = OrderStatus::find($order->getOriginal('orderstatus_id');
if ($oldStatus->name !== 'cancelled' && $order->orderstatus->name === 'cancelled') {
$order->products->each(function(Product $product) {
$stock = $product->getAttribute('stock');
$product->update(['stock' => $stock + $product->order->getAttribute('quantity_of_product_ordered')]);
});
}
// added to order table similar to above...
// check if it's a new product id being added to the order, decrease stock quantity accordingly...
// ...
});
}
SOLVED
the trick was to use try { on my CartController when I wanted to save my data in orders table there I should place my codes like:
try {
$order = new Order();
$qty = Cart::getTotalQuantity();
$order->product_data = $cartItems;
$order->user_id = Auth::user()->id;
// rest of it...
Auth::user()->orders()->save($order);
//trick is in this part
foreach ($cartItems as $item) {
$product = Product::find($item->id);
$product->decrement('stock', $item->quantity);
}
the answer was provided here

Having problems making a query in one to many Relationship in Laravel 4

This is pretty weird and I have no idea what i'm doing wrong.
I have 2 models:
class Project extends Eloquent {
public function status()
{
return $this->belongsTo('ProjectStatus','status_id');
}
}
and
class ProjectStatus extends Eloquent {
protected $table = 'PStatus';
public function projects()
{
return $this->hasMany('Project');
}
}
The table "projects" has the proper foreign keys:
Schema::create('PStatus', function($table) {
$table->increments('id');
$table->string('name', 64);
$table->unique('name');
});
Schema::create('Projects', function($table) {
$table->increments('id');
$table->string('name', 100);
$table->integer('status_id')->unsigned();
$table->foreign('status_id')->references('id')
->on('PStatus')
->onDelete('cascade');
});
In the database (for example) I have only 1 project: "Project_1" (id = 1) with status_id = 1 (Lets say status name = "Open"). If I execute the following query:
$projects = Project::with(array('status' => function($query){
$query->where('name', '<>', 'Open');
}))->get();
I'm still getting the project in the results!!. This is the sql log:
array (size=3)
'query' => string 'select * from `PStatus` where `PStatus`.`id` in (?) and `name` <> ?' (length=67)
'bindings' =>
array (size=2)
0 => int 1
1 => string 'Open' (length=4)
'time' => float 0.36
if I print:
var_dump($projects->count());
I still get 1 project! How come?
I can easily solve my problem by changing the query to something like:
$projects = Project::where('status_id', '<>', 1)->get(); //assuming that status_id=1 => "Open"
but i prefer not to use ids directly when I guess the method with should work. What am I doing wrong here???
Actually this is the answer:
Eloquent Nested Relation with Some Constraint
A huge confusion with the with method. I should have used a join.

Resources