Laravel - Many to Many - Model binding - laravel

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.

Related

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.

Add Products/Quantity to Stock Management In Laravel 5.4

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?

update user avatar with laravel5

From the look of it seems to me very logic but I am missing something, it doesn't work, nothing changes!
Here is my profile controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Image;
class ProfileController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile')->with('user', $user);
}
public function edit()
{
$user = Auth::user();
return view('edit')->with('user', $user);
}
public function update(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save(public_path('/uploads/users_avatars/'.$filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return redirect('profile')->with('user', Auth::user());
}
}
and here is my edit.blade.php
#extends('layouts.app')
#section('content')
<div class="col-md-6">
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('number', 'Phone') !!}
{!! Form::text('number', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group col-md-5">
{!! Form::label('avatar', 'Avatar') !!}
{!! Form::file('avatar', ['class'=>'form-control']) !!}
</div><br><br><br><br>
<div class="form-group">
{!! Form::submit('Update', null, ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
but when I edit the user it doesn't change..plz help
It seems like you have made a mistake while using Form from Laravel HTML Collective. You should use "files" => true instead of "file" => true
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}

Inserting data to related models

How to add a new data into related table ? I have two tables, the first is Edisi (Edition in English) table and Jurnal (Journal in English) table. The edisi table will contains many jurnal data, or in English the Edition table will contain many Journals data. My question is, how is the method create and save would look like ? I have created the function but it's not working.
Edisi table :
class CreateTableEdisi extends Migration
{
public function up()
{
Schema::create('edisi', function (Blueprint $table) {
$table->increments('id');
$table->string('judul')->unique();
$table->text('cover')->nullable();
$table->timestamps();
});
//Set FK di kolom id_edisi di table Jurnal
Schema::table('jurnal', function(Blueprint $table) {
$table->foreign('id_edisi')->references('id')->on('edisi')->onDelete('cascade')->onUpdate('cascade');
});
}
public function down()
{
Schema::table('jurnal', function(Blueprint $table) {
$table->dropForeign('jurnal_id_edisi_foreign');
});
Schema::drop('edisi');
}
}
Jurnal table :
class CreateTableJurnal extends Migration
{
public function up()
{
Schema::create('jurnal', function (Blueprint $table) {
$table->increments('id');
$table->string('judul', 200);
$table->string('penulis');
$table->text('abstrak');
$table->text('file');
$table->integer('id_edisi')->unsigned();
$table->timestamps();
});
}
public function down()
{
Schema::drop('jurnal');
}
}
Controller :
public function create()
{
return view('jurnal/create');
}
public function store(JurnalRequest $request)
{
$input = $request->all();
//Input PDF
if ($request->hasFile('file')) {
$input['file'] = $this->uploadPDF($request);
}
//Insert data jurnal
$jurnal = Jurnal::create($input);
return redirect('jurnal');
}
Show View :
#extends('template')
#section('main')
<div class="container sitecontainer single-wrapper bgw">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12 m22">
<div class="widget searchwidget joblist">
<div class="large-widget m30">
<div class="post row clearfix">
<div class="col-md-4">
<div class="post-media">
<img alt="" src="{{ asset('fotoupload/' . $edisi->cover) }}" class="img-responsive">
<a class="btn btn-primary btn-block">{{ $edisi->judul }}</a>
</div>
</div>
<div class="col-md-8">
<div id="siswa">
<h2>Daftar Jurnal</h2>
#if (count($jurnal_list) > 0)
<table class="table">
<thead>
<tr>
<th>Judul</th>
<th>Penulis</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach ($jurnal_list as $jurnal): ?>
<tr>
<td>{{ $jurnal->judul }}</td>
<td>{{ $jurnal->penulis }}</td>
<td>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id, 'Detail', ['class' => 'btn btn-success btn-sm']) }}
</div>
<div class="box-button">
{{ link_to('jurnal/' . $jurnal->id . '/edit', 'Edit', ['class' => 'btn btn-warning btn-sm']) }}
</div>
<div class="box-button">
{!! Form::open(['method' => 'DELETE', 'action' => ['JurnalController#destroy', $jurnal->id]]) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger btn-sm']) !!}
{!! Form::close() !!}
</div>
</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
#else
<p>No Journals yet.</p>
#endif
<div class="tombol-nav">
Add new Journal to this edition
</div>
</div> <!-- / #jurnal -->
</div>
</div><!-- end post -->
</div><!-- end large-widget -->
</div><!-- end widget -->
</div><!-- end col -->
</div><!-- end row -->
</div><!-- end container -->
#stop
I'm new to Laravel and I'm stuck here. I tried everything I could (look at the controller) and when I try to add the journal data in the selected edition, it shows me error Constrains Fails. Thanks for your help!
First change $table->integer('id_edisi')->unsigned(); on your "jurnal" table to $table->integer('edisi_id')->unsigned();
Then add following method to "Jurnal" model
public function edisi()
{
return $this->belongsTo('App\Edisi');
}
if you don't like to change jurnal table as I showed earlier, modify above method as follows
public function edisi()
{
return $this->belongsTo('App\Edisi', 'id_edisi');
}
Then in controller
$jurnal_list = Jurnal::with('edisi')->get();
If you want to access "jurnal" from "edisi" add following method to the "Edisi" model
public function jurnals()
{
return $this->hasMany('App\Jurnal');
}
or for unmodified jurnals table.
public function jurnals()
{
return $this->hasMany('App\Jurnal', 'id_edisi');
}
Then in controller
$jurnal_list = Edisi::with('jurnals')->get();
Note: make sure to add $table variable to "Jurnal" and "Edisi" models, because normally table name needs be like s(ex:- Model: Post Table: posts, Model: Comment Table: comments)

Undefined variable: section (View: D:\xampp\htdocs\laravel5\resources\views\cms\sections.blade.php)

I try to made simple crud and found this error
Undefined variable: section
(View:D:\xampp\htdocs\laravel5\resources\views\cms\sections.blade.php)
Route:
Route::resource('sections','SectionsController');
View:
{!! Form::open(["url"=>"sections","files" => "true"]) !!}
section name: {!! Form::text("section_name")!!}
<hr/>
{!! Form::file('image',["class"=>"filestyle","data-buttonText"=>"select image","data-input"=>"false"]) !!}
<br/>
{!! Form::submit("insert#upload",["class"=>"btn btn-primary"]) !!}
{!! Form::close() !!}
<div class="row">
<h3>get data from db ::</h3>
#foreach($sections as $section)
<div class="col-md-3">
<div class="thumbnail">
<p>{{$section->section_name}}</p>
<img src="/uploads/{{$section->image_name}}" width="90%" height="90%">
</div>
</div>
#endforeach
</div>
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "patch"]) !!}
{!! Form::text("section_name",$section->section_name)!!}
{!! Form::submit("update",["class"=>"btn btn-success"]) !!}
{!! Form::close() !!}
</div>
</div>
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "delete"]) !!}
{!! Form::submit("delete",["class"=>"btn btn-danger"]) !!}
{!! Form::close() !!}
</div>
</div>
</div>
Controller:
use DB;
use Input;
use Validator;
class SectionsController extends Controller {
public function index() {
$section=DB::table('sections')->get();
return view('cms.sections')->withSections($section);
}
public function create() {
return view('cms.sections');
}
public function store(Request $request) {
$this->validate($request,
['section_name' => 'required|unique:sections,section_name|max:20',
'image' => 'mimes:jpeg|max:1024']);
$section_name=$request->input('section_name');
$file=$request->file('image');
$destinationPath='uploads';
$filename=$file->getClientOriginalName();
$file->move($destinationPath,$filename);
$rules = array('image' => 'mimes:jpg,png,gif|required|max:10000');
$validator = Validator::make(Input::all(), $rules);
DB::table('sections')->insert(['section_name' => $section_name,
'image_name' => $filename]);
return redirect('sections');
}
public function update(Request $request, $id) {
$section_name=$request->input('section_name');
DB::table('sections')->where('id',$id)->update(['section_name'=>$section_name]);
return redirect('sections');
}
public function destroy($id) {
DB::table('sections')->where('id',$id)->delete();
return redirect('sections');
}
}
There is one definite problem in your View code: You use $section after you end your #foreach block that defines it, for example here:
#foreach($sections as $section)
...
#endforeach
...
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
{!! Form::open(["url"=>"sections/$section->id","method" => "patch"]) !!}
------------------------------------^^^^^^^^
I suspect you intended to place the <div class="row"> blocks inside your #foreach block.

Resources