Add Products/Quantity to Stock Management In Laravel 5.4 - laravel

I'm developing Inventory System Using Laravel 5.4. I need help. I've a product table and stock table. If the user tried to add a product to stock whereby the supplier_id and product_id already exist i.e (Select quantity FROM Stocks WHERE supplier_id=1 AND product_id=1) The product should be added to the quantity column of the existing stock instead of inserting the product and quantity into another column.
i.e if Stock table has --> ProductName == Laptop; SupplierID==1; Quantity ==(50). If the user select ProductName == Laptop; AND SupplierID==1; The Quantity Coulmn should be sum to ( 50) Inserting should ONLY be when ProductName and Supplier doesn't exist in same row i.e (Select quantity FROM Stocks WHERE supplier_id=20 AND product_id=2) .
How can I use Eloquent effectively to achieve this pls
Product Table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('brand_id')->index()->unsigned()->nullable();
$table->string('name');
$table->string('part_number');
$table->string('serial_number');
$table->timestamps();
});
STOCK TABLE
Schema::create('stocks', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->index()->unsigned()->nullable();
$table->integer('category_id')->index()->unsigned()->nullable();
$table->integer('supplier_id')->index()->unsigned()->nullable();
$table->string('quantity');
$table->string('unit_price');
$table->date('purchased_date');
$table->timestamps();
$table->date('delete_at');
});
My StockController :;
public function create(Request $request)
{
$products= Product::lists('name', 'id')->all();
$categories= Category::lists('name', 'id')->all();
$suppliers= Supplier::lists('name', 'id')->all();
return view('admin.stocks.create', compact('products','categories','suppliers'));
}
public function store(Request $request)
{
Stock::create($request->all());
return redirect('/admin/stocks');
}
create.blade.php
{!! Form::open(['method'=>'POST', 'action'=> 'StocksController#store','files'=>true]) !!}
<div class="form-group">
{!! Form::label('supplier_id', 'Supplier/Vendor:') !!}
{!! Form::select('supplier_id', [''=>'Select Supplier'] + $suppliers, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('product_id', 'Part Name:') !!}
{!! Form::select('product_id', [''=>'Select Part Name'] + $products, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id', [''=>'Choose Category'] + $categories, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('quantity', 'Quantity:') !!}
{!! Form::text('quantity', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('purchased_date', 'Purchased Date:') !!}
{!! Form::text('purchased_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('unit_price', 'Unit Price (Naira):') !!}
{!! Form::text('unit_price', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Add Stock', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I hope someone can help me out.

Your store method in StockController need to be like this:
public function store(Request $request)
{
$stock = Stock::where([
['product_id', '=', $request->product_id],
['supplier_id', '=', $request->supplier_id]
])->first();
if ($stock) {
$stock->increment('quantity', $request->quantity);
} else {
Stock::create($request->all());
}
return redirect('/admin/stocks');
}
Think this will fix problem, but check what you do with unit_price and purchase_date in case of updating same row?

Related

QueryException error while updating data

Into database not update data, i can't understand my problem, error is below
Illuminate \ Database \ QueryException (42S22)
SQLSTATE[42S22]: Column not found: 1054 Unknown column '_method' in 'field list' (SQL: update trades set _method = PATCH, _token = AcbGEbEyNxX3e2RzRR2cb1SW6NDvkJuDqFevl0Mr, exchange_id = 1, market_id = 1, symbol_id = 45, is_action = 0, tradedate = , rate = 5000, note = hhhhhhhhh, updated_at = 2018-07-21 13:06:13 where trades.user_id = 33 and trades.user_id is not null and trades.deleted_at is null)
This is my controller
public function edit($id)
{
$trade = Trade::findOrFail($id);
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$symbols = Symbol::pluck('symbol','id')->all();
$reasons = Reason::pluck('reason','id')->all();
return view('member.add-single-trade.edit', compact('trade','reasons', 'exchanges', 'markets', 'symbols'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$tradeID= Auth::user()->trade($id)->update($input);
$reasons=$request->input('reason');
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
$data = array(
'reason_id' =>$reasons,
'trade_id' => $tradeID->id,
);
$test['trade_id']= $tradeID->id;
if($data > 0) {
foreach ($data as $datum) {
$tradeID->tradereason()->update(new TradeReason($datum));
}
}
}
This is my edit.blade.php file
{!! Form::model($trade,['method'=>'PATCH', 'action'=> ['trades\AddSingleTradeController#update',$trade->id]]) !!}
<div class="col-sm-10">
<div class="form-group col-sm-5">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] + $markets, null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbols:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options']+ $symbals , null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{{ Form::radio('is_action', 1) }} Buy
{{ Form::radio('is_action', 0) }} Sell
</div>
<div class="form-group col-lg-5">
{!! Form::label('tradedate', 'Traded date:') !!}
{!! Form::date('tradedate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-lg-5">
{!! Form::label('rate', 'Traded Rate:') !!}
{!! Form::text('rate', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('reason', 'Choose Reasons:') !!}
{{Form::select('reason',$reasons,null, array('id'=>'reasons','multiple'=>'multiple','name'=>'reason[]',"class"=>"js-example-basic-multiple form-control", 'data-width'=>'60%', 'data-live-search'=>'true','onchange' => 'all_function()'))}}
</div>
<div class="form-group col-lg-10">
{!! Form::label('note', 'Note:') !!}
{!! Form::textarea('note', null, ['class'=>'form-control', 'rows' => 2, 'cols' => 40])!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Save', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
<div class="form-group col-lg-4">
{!! Form::open(['method'=>'DELETE', 'action'=> ['trades\AddSingleTradeController#destroy', $trade->id]]) !!}
<div class="form-group">
{!! Form::submit('Delete', ['class'=>'btn btn-danger btn-lg']) !!}
</div>
</div>
{!! Form::close() !!}
This is my create.blade.php file
<td>{{$trade->stoploss}}</td>
You haven't included your model code (probably you are using $guarded = [];) but probably instead of
$input = $request->all();
you should use:
$input = $request->except('_method');
This is because additional _method field is added to form to pass HTTP verb method when using Form::model and obviously you don't have _method field in your table
EDIT
In case you have more fields you can include more fields to ignore for example:
$input = $request->except('_method', '_token');
or you can only use get fields you really want to get for example:
$input = $request->only('exchange_id', 'market_id');
(Of course you should add more fields to above - this is only example)
You can use $fillable property of the model to tell ORM which attributes (columns) can be mass assignable. Any other fields passed via update and create methods will be discarded. check at Laravel docs

Search query through foreign key

I'm trying to search through my comments on the username connected to the user_id Foreign Key
Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{
public function author()
{
return $this->belongsTo('App\User','user_id');
}
}
Controller:
public function index(Request $request)
{
$comments = Comment::query()->orderby('created_at', 'DESC');
$id=$request->]
return view('comments.index')->withComment($comment);
}
View:
<div class="panel-body">
{!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
<div class="col-md-5">
{!! Form::label('id', 'Search By ID:') !!}
{!! Form::text('id', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-5">
{!! Form::label('username', 'Search By Username:') !!}
{!! Form::text('username', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-2">
{!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
</div>
{!!Form::close()!!}
</div>
#foreach($comment as $comments)
//data
#endforeach
I believe it is failing at the builder level because you are trying to query on an object that is not yet known. IE the author LIKE must be part of a sub query:
$comments = Comment::whereHas('author', function ($query) use($request) {
$query->where(users.username, 'LIKE', $request->input('username') )
}])->orderby('created_at', 'DESC')->get();
I see you will have to write the query a second time, but I think this may be successful for you.

Values from from select form field not updating in laravel

I have a form that with select items from another table. The items list just fine in form view. The problem I am encountering is that the other fields in the form updates just fine except the drop-down lists.
I have checked and confirmed that the fields are all include in the $fillable array in the model.
When i dd($myinputVariable), its showing values of all form inputs.
This my form.
{!! Form::model($member, [
'method' => 'PATCH','id'=>'member-regform',
'route' => ['members.update', $member->member_registration_number]
]) !!}
<div class="form-group">
{!! Form::label('constituency_id','Constituency') !!}
{!! Form::select('constituency_id',$constituencies,
array('require','class'=>'form-control'))!!}
</div>
<div class="form-group">
{!! Form::label('ward_id','Ward') !!}
{!! Form::select('ward_id',$wards,
array('require','class'=>'form-control'))!!}
</div>
<div class="form-group pull-right">
{!! Form::submit('Save Changes',
array('class'=>'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
My controller
public function __construct()
{
$this->constituencies = Constituency::where('county_id',8)->pluck('const_name','id');
$this->wards = Ward::pluck('ward','id');
}
public function update(Request $request, $id)
{
//
$member = Member::where('member_registration_number',$id)->first();
$input = $request->all();
$member->fill($input)->save();
Session::flash('message', 'Member successfully updated!');
return redirect()->back();
}
My Model
protected $fillable = array('constituency_id','ward_id');
After selecting a different ward_id or constituency_id, the value does not change from the older one after update. This issue has troubled my head for hours. Kindly help.
The 3rd element should be the selected value and the options the 4th:
{!! Form::select('ward_id', $wards, null, ['require', 'class' => 'form-control']) !!}
LaravalCollective drop downs

Laravel 5.2, carry over article ID to next page and insert into database field

I am trying to use Laravel 5.2 to add questions to an article. Currently I can edit the article, using the edit function in the ArticleController. I want to have a button on the Article edit view, that allows the user to add a question. So when this is clicked, I need it to take the user to /articles/questions/create, but it needs to bring the ID for the article it has just come from with it, so it can be automatically stored in the article_id field in the db table. How would I do this, currently I can store the article ID by manually typing the in a text box on the creation form. Obviously, the aim is for the user to not have to know the ID of the article, and for it to be added automatically.
My Create function so far:
public function create(){
$questions = Question::all();
$users = User::all();
$articles = DB::table('article')->where('id', 'article_id')->get();
return view('articles/questions/create', ['question' => $questions], ['users' => $users], ['article' => $articles]);
}
The form so far:
<h1>Create & Add Question</h1>
{!! Form::open(array('action' => 'QuestionController#store', 'id' => 'createquestion')) !!}
{{ Form::hidden(csrf_token()) }}
<div class="row col-sm-12 col-lg-12">
{!! Form::label('article_id', 'Article ID:') !!}
{!! Form::text('article_id', null, ['class' => 'large-8 columns']) !!}
</div>
<div class="row col-sm-12 col-lg-12">
{!! Form::label('title', 'Question:') !!}
{!! Form::textarea('title', null, ['class' => 'large-8 columns']) !!}
</div>
<div class="row col-sm-12 col-lg-12">
{!! Form::label('require', 'Required?') !!}
{{ Form::radio('require', 1) }} Yes <br>
{{ Form::radio('require', 0) }} No
</div>
<br>
<div class="row large-4 columns">
{!! Form::submit('Add Question', ['class' => 'button']) !!}
</div>
{!! Form::close() !!}
The form does successfully post the the Database, I just need the ID to automatically insert so that the article can reference it to show the question on the article page.
First of all edit the below lines
$articles = DB::table('article')->where('id', 'article_id')->get();
return view('articles/questions/create', ['question' => $questions], ['users' => $users], ['article' => $articles]);
to
$articles = DB::table('article')->where('id', 'article_id')->first();
return view('articles/questions/create', ['question' => $questions, 'users' => $users, 'article' => $articles]);
Now, take a hidden field in the form you posted above
{!! Form::hidden('article_id', $article->id) !!}
and finally access the article id in your store method.
public function store(Request $request){
$article_id = $request->article_id
}

Laravel - Many to Many - Model binding

I need some help.
I have these tables: users, buys and codecs. I have a many-to-many relationship: buys, codecs, buy_codec
Tables
Schema::create('codecs', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('buys', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
});
Schema::create('buy_codec', function (Blueprint $table) {
$table->increments('id');
$table->integer('buy_id')->unsigned();
$table->foreign('buy_id')->references('id')->on('buys')->onDelete('cascade');
$table->integer('codec_id')->unsigned();
$table->foreign('codec_id')->references('id')->on('codecs')->onDelete('cascade');
$table->timestamps();
});
This is my controller:
class UserBuyController extends Controller
{
public function create($userId)
{
$codecs = Codec::lists('name', 'id');
$usr = User::findOrFail($userId);
return view('buy.create', compact('usr', 'codecs'));
}
public function store($userId, Request $request)
{
$codecs = $request->input('codecs');
$usr = User::findOrFail($userId)->buy()->create($request->except('codecs'));
$usr->codec()->sync($codecs);
return redirect('user/'.$userId.'/buy');
}
public function edit($userId, $id)
{
$codecs = Codec::lists('name', 'id');
$buy = User::findOrFail($userId)->buy()->findOrFail($id);
return view('buy.edit', compact('buy', 'codecs'));
}
}
Create form
{!! Form::open(['method'=>'POST', 'action'=>['UserBuyController#store', $usr->id]]) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-font"></i></span>
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('codecs', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
{!! Form::submit('Submit', ['class'=>'btn btn-info']) !!}
{!! Form::close() !!}
And this is the edit form
{!! Form::model($buy,['url'=>url('user/'.$buy->user->id.'/buy/'.$buy->id),'method'=>'patch']) !!}
<div class="form-group">
{!! Form::label('name', 'Name:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-font"></i></span>
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('codecs', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
{!! Form::submit('Update', ['class'=>'btn btn-info']) !!}
{!! Form::close() !!}
Model binding doesn't work
Something is wrong but I don't know what.
This is my pivot table. I have 2 codecs associated with buy_id 3
And this is my edit page.
Nothing is selected.
Update
Model
class Buy extends Model
{
protected $guarded = ['id'];
public function codec() {
return $this->belongsToMany('App\Codec');
}
public function user() {
return $this->belongsTo('App\User');
}
}
class Codec extends Model
{
protected $guarded = ['id'];
public function buy() {
return $this->belongsToMany('App\Buy');
}
}
class User extends Authenticatable
{
public function buy() {
return $this->hasMany('App\Buy');
}
}
One solution would be to create an accessor for the codec ids and use that with Form::select() instead:
In your Buy model add the following accessor:
public function getCodecListAttribute()
{
return $this->codecs->pluck('id')->toArray();
}
Then change you select block to:
<div class="form-group">
{!! Form::label('codec_list', 'Outbound Codecs:') !!}
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-language"></i></span>
{!! Form::select('codec_list[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}
</div>
</div>
This will mean that when you try to get the value from the request you will have to use codec_list instead of codecs.
Hope this helps!
in the edit form: {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!} the default selected value is set as null. You should set here the list of ids of the associated codecs.
Hope this helps.

Resources