Laravel 5.4 Multiple upload and Inserting data - laravel

Hello everyone and thank you in advance, first of all sorry if my code is so confused I am still learning ^^.
I am trying to make a product with different attribute plus 3 different images(making the product gallery) and a feature image,
I have succeed to create the attributes and feature image.
The problem is with the 3 image for the gallery I cant store (neither in DB or image folder)
I have Two tables (product and productgallery) the relation between them is hasMany (I am using Laravel 5.4)
This the error I got after run the code
SQLSTATE[HY000]: General error: 1364 Field 'product_id' doesn't have a default value (SQL: insert into `product_galleries` (`updated_at`, `created_at`) values (2017-05-13 20:58:20, 2017-05-13 20:58:20))
(sorry for my English which for sure will make it harder to understand my question)
ProductController
public function store(UploadRequest $request)
{
$product = new Product();
$product->product_name = $request->product_name;
$product->product_description = $request->product_description;
if($request->hasFile('product_preview')) {
$file = Input::file('product_preview');
$filename = time(). '-' .$file->getClientOriginalName();
$product->product_preview = $filename;
$file->move(public_path().'/images/product-feature', $filename);
}
$product->category_id = $request->category_id;
$product->color_id = $request->color_id;
$product->size_id = $request->size_id;
$product->material_id = $request->material_id;
// $product->fantasia_id = $request->fantasia_id;
$productgallery = new ProductGallery();
if($request->hasFile('fileToUpload[]')) {
$files = Input::file('fileToUpload[]');
foreach ($request->$files as $photo) {
$filename = time(). '-' .$photo->getClientOriginalName();
$productgallery->product_images = $filename;
$photo->move(public_path().'/images/product-gallery', $filename);
$productgallery->product_id = 1;
}
}
$product->save();
$productgallery->save();
return $this->create()->with('success', 'Uploaded Successfully');
}
Upload request (FormRequest)
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UploadRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$rules = [
'product_name' => 'required|max:120',
'category_id' => 'required|integer',
'product_preview' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
];
$fileToUpload = count($this->input('fileToUpload'));
foreach(range(0, $fileToUpload) as $index) {
$rules['fileToUpload.' . $index] = 'image|mimes:jpeg,bmp,png|max:2000';
}
return $rules;
}
}
the view for the form
#extends('layouts.backend-master')
#section('styles')
<link rel="stylesheet" href="">
#endsection
#section('content')
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<h1>Add a new product</h1>
<form action="{{route('products.store')}}" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="product_name">Name of the product</label>
<input type="text" name="product_name" id="product_name"/>
</div>
<div class="input-group">
<label for="product_description">Product Description</label>
<textarea type="text" name="product_description" id="product_description" rows="8"></textarea>
</div>
<div class="input-group">
<label for="product_preview">Feature Image:</label>
<input type="file" name="product_preview" id="file">
</div>
<div class="input-group">
<label for="category_id">Category</label>
<select name="category_id" id="category_id">
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->category_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="color_id">Color</label>
<select name="color_id" id="color_id">
#foreach($colors as $color)
<option value="{{ $color->id }}">{{ $color->color_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="size_id">Size</label>
<select name="size_id" id="size_id">
#foreach($sizes as $size)
<option value="{{ $size->id }}">{{ $size->size_name }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="material_id">Material</label>
<select name="material_id" id="material_id">
#foreach($materials as $material)
<option value="{{ $material->id }}">{{ $material->material_type }}</option>
#endforeach
</select>
</div>
<div class="input-group">
<label for="fileToUpload">Product Gallery:</label>
<input type="file" name="fileToUpload[]" id="fileToUpload" multiple >
</div>
<button type="submit" class="btn">Add</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
#endsection
#section('scripts')
#endsection
thank you

You'll need to look at Laravel relationships API documentation. Here's a link to read more about it Laravel 5.4 Eloquent Relationships
Quick tip to fix that
You should add a foreign key in your database/migration file
For a migration you can simply add
$table->foreign('product_id')->references('id')->on('products');
And add this method to your Product model
public function productgallery(){
return $this->hasMany(Productgallery::class);
}
and this to your Productgallery model
public function product(){
return $this->belongsTo(Product::class);
}
Note: You'll still need to populate the product_id field within your request
Package solution
I'd recommend you use a 3rd party package for that matter, as it will be less work, cleaner and more solid to use.
You can look more into spatie's medialibrary for Laravel

I think this is what you want.
This will create a new Product and create a new ProductGallery for each image passed in $request->file('fileToUpload[]'):
$product = new Product();
$product->product_name = $request->product_name;
$product->product_description = $request->product_description;
if($request->hasFile('product_preview')) {
$file = Input::file('product_preview');
$filename = time(). '-' .$file->getClientOriginalName();
$product->product_preview = $filename;
$file->move(public_path().'/images/product-feature', $filename);
}
$product->category_id = $request->category_id;
$product->color_id = $request->color_id;
$product->size_id = $request->size_id;
$product->material_id = $request->material_id;
// $product->fantasia_id = $request->fantasia_id;
// First save the product (so that you have it's ID)
$product->save();
// Then create galleries
if($request->hasFile('fileToUpload[]')) {
$files = Input::file('fileToUpload[]');
foreach ($files as $photo) {
$productgallery = new ProductGallery();
$filename = time(). '-' .$photo->getClientOriginalName();
$productgallery->product_images = $filename;
$photo->move(public_path().'/images/product-gallery', $filename);
$productgallery->product_id = $product->id; // Save it to the newly created product
$productgallery->save();
}
}
return $this->create()->with('success', 'Uploaded Successfully');

Related

Laravel Update DB with array from views

i'm doing a simple project but having some difficulties with updating my database with values that I get from a form. The project is having a list of movies and when you click on one it would take you to a page with more details. Theres a button which you can update the details of that movie. I'm trying save whatever details are made to the relevant index of the table using the id. I can't seem to get it to work though. I did something similar when creating a new entry but having some difficulty updating the values of a specific movie/page. Thanks for any help!
Route:
Route::get('catalog', 'App\Http\Controllers\CatalogController#getIndex');
Route::get('catalog/show/{id}', 'App\Http\Controllers\CatalogController#getShow');
Route::get('catalog/create', 'App\Http\Controllers\CatalogController#getCreate');
Route::get('catalog/edit/{id}', 'App\Http\Controllers\CatalogController#getEdit');
Route::post('catalog/create', 'App\Http\Controllers\CatalogController#postCreate');
Route::put('catalog/edit/{id}','App\Http\Controllers\CatalogController#putEdit');
Controller:
public function getEdit($id)
{
return view('catalog.edit', ['arrayPeliculas' => Movie::all()]);
}
public function getCreate()
{
return view('catalog.create');
}
public function postCreate(Request $request)
{
$Movie = new Movie;
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
public function putEdit(Request $request, $id)
{
$Movie = new Movie;
$Movie[$id]->title = $request->title;
$Movie[$id]->year = $request->year;
$Movie[$id]->director = $request->director;
$Movie[$id]->poster = $request->poster;
$Movie[$id]->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Edit page:
<form method="PUT">
{{ method_field('PUT') }}
{{-- TODO: Protección contra CSRF --}}
{{ csrf_field() }}
<div class="form-group">
<label for="modificar">Modificar Pelicula</label>
<input type="text" name="title" id="title" class="form-control" value="{{ $arrayPeliculas[$id]->title }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el año --}}
<label for="Año">Año</label>
<input type="text" name="year" id="year" class="form-control" value="{{ $arrayPeliculas[$id]->year }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el director --}}
<label for="Director">Director</label>
<input type="text" name="director" id="directo" class="form-control" value="{{ $arrayPeliculas[$id]->director }}">
</div>
<div class="form-group">
{{-- TODO: Completa el input para el poster --}}
<label for="Poster">Poster</label>
<input type="text" name="poster" id="poster" class="form-control" value="{{ $arrayPeliculas[$id]->poster }}">
</div>
<div class="form-group">
<label for="synopsis">Resumen</label>
<textarea name="synopsis" id="synopsis" class="form-control" rows="3" >{{ $arrayPeliculas[$id]->synopsis }}"</textarea>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-primary" style="padding:8px 100px;margin-top:25px;">
Añadir película
</button>
</div>
</form>
I tried a few other things like->update but I can't seem to get it to work properly.
To update an existing model, first find() it.
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->title = $request->title;
$Movie->year = $request->year;
$Movie->director = $request->director;
$Movie->poster = $request->poster;
$Movie->synopsis = $request->synopsis;
$Movie->save();
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
Using the update function should also work then:
public function putEdit(Request $request, $id)
{
$Movie = Movie::find($id);
$Movie->update([
'title' => $request->title,
'year' => $request->year,
'director' => $request->director,
'poster' => $request->poster,
'synopsis' => $request->synopsis,
]);
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}
You could really simplify it with some Laravel magic like Route Model Binding...
Route::put('catalog/edit/{movie}','App\Http\Controllers\CatalogController#putEdit');
...
public function putEdit(Request $request, Movie $movie)
{
$movie->update($request->all());
return redirect()->action('App\Http\Controllers\CatalogController#getIndex');
}

How to use select2 multiselect with livewire

What I am trying to achieve is, there are two models A and B with a relationship of One to many, where A has many B. So if the records for A and B have already been created, A can be assigned to many B. So I started this current project with livewire, and now I am at a loss. Normal select with multiple works just fine and populates the array in the backend of livewire. But when I use select2 nothing is stored in the array, and when I dd it, it shows an empty array.
Even though livewire provides wonderful set of tools, I am starting to realize that there is a lot of gray areas where things are missing or lacks external support, like select2 here.
Here is what I have done so far:
<div>
<div class="tab-pane fade show active" id="card1" role="tabpanel" aria-labelledby="card1-tab">
<div class="pt-3"></div>
<div class="row" >
<div class="form-group col">
<label for="cards">Enter Cards</label>
<select class="form-control select2" id="cards" multiple="multiple" onchange="this.dispatchEvent(new InputEvent('input'))>
<option disabled="">Select Cards</option>
#foreach($cardsUnassigned as $card)
<option value="{{ $card->id }}">{{ $card->imei_number }}</option>
#endforeach
</select>
</div>
<div class="form-group col">
<label for="technicians" class="">Technicians</label>
<select class="form-control select2" id="technicians" wire:model='techies.'>
<option disabled="">Select Technicians</option>
#foreach($technicians as $tech)
<option value="{{ $tech->id }}">{{ $tech->first_name }}</option>
#endforeach
</select>
</div>
</div>
#foreach($cardSelect as $key => $value)
{{$value}}
#endforeach
<button wire:click="assignCardToTech()" class="btn btn-primary">Submit</button>
</div>
</div>
#push('scripts')
<script>
$('#cards').select2({
placeholder: 'Select Cards to assign'
});
//send data to livewire
$('#technicians').select2({
placeholder: 'Select Technicians'
});
</script>
#endpush
And the backend:
<?php
namespace App\Http\Livewire\Stock\Assigns;
use App\Models\Card;
use App\Models\Sim;
use App\Models\Technician;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Auth;
class Assigns extends Component
{
public $sortBy_card = 'imei_number';
public $sortBy_sim = 'ip';
public $sortDirection = 'asc';
public $search = '';
public $perPage = 10;
public $cardSelect = [];
public $techies;
public function render()
{
$simsUnassigned = Sim::query()
->whereNull('technician_id')
->searchUnassigned($this->search)
->get();
$cardsUnassigned = Card::query()
->whereNull('technician_id')
->searchUnassignedCard($this->search)
->get();
// dd($cardsUnassigned);
$simsAssigned = Sim::query()
->searchAssigned($this->search)
->orderBy($this->sortBy_sim, $this->sortDirection)
->paginate($this->perPage);
$cardsAssigned = Card::query()
->searchAssignedCard($this->search)
->orderBy($this->sortBy_card, $this->sortDirection)
->paginate($this->perPage);
$technicians = Technician::query()->get();
return view('livewire.stock.assigns.assigns',compact('simsUnassigned','cardsUnassigned','simsAssigned','cardsAssigned','technicians'))
->extends('layouts.base')
->section('content');
}
public function assignCardToTech(){
dd($this->cardSelect);
if($this->cards){
foreach($this->cards as $card){
}
}
}
}
Hopefully this helps.
######## INSIDE LIVEWIRE COMPONENT
public array $locationUsers = [];
protected $listeners = ['locationUsersSelected'];
public function locationUsersSelected($locationUsersValues)
{
$this->locationUsers = $locationUsersValues;
}
######## INSIDE LIVEWIRE BLADE
<div class="col-md-12 mb-3" wire:ignore>
<label for="locationUsers">Select Users</label>
<select id="locationUsers" class="form-control select2" multiple="multiple">
<option value="">--select--</option>
#foreach($this->users as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
######## INSIDE LIVEWIRE SCRIPTS
document.addEventListener('livewire:load', function () {
$('#locationUsers').on('select2:close', (e) => {
#this.emit('locationUsersSelected', $('#locationUsers').select2('val'));
});
$('#locationUsers').val(#this.get('locationUsers')).trigger('change');
});
Your could try adding this to your html
<div class="form-group col-md-6" wire:ignore>
<label for="manager" class="mb-0 h5">Assign Managers:</label>
<select wire:model="reporting_managers" id="manager" class="select-2 multiple='multiple' data-placeholder="Assign Managers">
#foreach ($managers as $manager)
<option value="{{ $manager->id }}" data-name="{{ $manager->name }}">{{ $manager->name }}</option>
#endforeach
</select>
</div>
and then in your javaScript section
$('#manager').on('select2:select', function (e) {
#this.set('reporting_managers', $('#manager').select2('val'));
});
$('#manager').on('select2:unselect', function (e) {
#this.set('reporting_managers', $('#manager').select2('val'));
});
This will directly store your selection in variable in livewire and won't get deselected on render.

CRUD Laravel Update in database one to many relationship

I have a CRUD app with cars and for every car I have fields to create a car and images to upload. Everithing is ok, I have one to many relationship and for a car I can have multiple images . When I create a car and I upload photos these photos are stored correctly in database and in my public/images director. The problem is when I want to make the UPDATE par, I don't know how to update the photos in database.
Here is my code, I have update function where I don't know exactly how to make the update .
My cars table:
Schema::create('cars', function (Blueprint $table) {
$table->id();
$table->string('model');
$table->integer('seats');
$table->string('fuel');
$table->integer('year');
$table->string('color');
$table->string('gearbox');
$table->integer('price');
$table->string('coinType');
$table->timestamps();
});
My images table
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->integer('car_id');
$table->string('file_name');
$table->timestamps();
});
My Car model:
class Car extends Model
{
protected $fillable = [
'model',
'seats',
'fuel',
'year',
'color',
'gearbox',
'price',
'coinType',
];
public function images()
{
return $this->hasMany(Image::class);
}
use HasFactory;
}
My Image model:
class Image extends Model
{
protected $fillable = [
'car_id',
'file_name'
];
public function car()
{
return $this->belongsTo(Car::class);
}
use HasFactory;
}
My edit.blade:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h2 class="display-3">Edit a car</h2>
<div>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div><br />
#endif
<form method="post" action="{{ url('cars/'. $res->id) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<legend>
<label for="model" class="col-form-label">Model :</label>
<input type="text" class="form-control" id="model" name="model" value="{{ $res->model }}">
</legend>
</div>
<div class="form-group ">
<legend>
<label for="seats" class="col-form-label">Seats :</label>
</legend>
<select name="seats" id="seats" value="{{ $res->seats }}">
<option value="2">2</option>
<option value="4" selected="selected">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="fuel" class="col-form-label">Fuel :</label>
</legend>
<select name="fuel" id="fuel" value="{{ $res->fuel }}">
<option value="benzine+gpl">benzine+gpl</option>
<option value="gpl" selected="selected">diesel</option>
<option value="diesel">gpl</option>
<option value="diesel+gpl">diesel+gpl</option>
<option value="benzine">benzine</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="year" class="col-form-label">Year :</label>
</legend>
<input type="text" name="year" id="year" value="{{ $res->year }}">
</div>
<div class="form-group">
<legend>
<label for="color" class="col-form-label">Color :</label>
</legend>
<input type="text" class="form-control" id="color" name="color" value="{{ $res->color }}">
</div>
<div class="form-group ">
<legend>
<label for="gearbox" class="col-form-label">Gearbox :</label>
</legend>
<select name="gearbox" id="gearbox" value="{{ $res->gearbox }}">
<option value="manual">manual</option>
<option value="automatic" selected="selected">automatic</option>
<option value="semiautomatic">semiautomatic</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="price" class="col-form-label">Price :</label>
</legend>
<input type="text" class="form-control" id="price" name="price" value="{{ $res->price }}">
</div>
<div class="form-group ">
<legend>
<label for="coinType" class="col-form-label">CoinType :</label>
</legend>
<select name="coinType" id="coinType" value="{{ $res->coinType }}">
<option value="EUR">EUR</option>
<option value="LEI" selected="selected">LEI</option>
<option value="USD">USD</option>
</select>
</div>
<div class="form-group ">
<legend>
<label for="image" class="col-form-label">Upload images :</label>
</legend>
<input type="file" class="form-control" name="images[]" multiple />
</div>
<hr style="height:2px;border-width:0;color:gray;background-color:gray">
<div class="col-xs-12 col-sm-12 col-md-12 ">
<button type="submit" class="btn btn-primary">Add car</button>
<a class="btn btn-primary" href="{{ route('cars.index') }}"> Back</a>
</div>
</div>
</form>
#endsection
My Controller:
public function store(Request $request)
{
$request->validate([
'model' => 'required',
'year' => 'required',
'color' => 'required',
'price'=> 'required',
'file_name.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$destionationPath = public_path('/images');
$images = [];
$car = new Car();
$car->model = $request->model;
$car->seats = $request->seats;
$car->fuel = $request->fuel;
$car->year = $request->year;
$car->color = $request->color;
$car->gearbox = $request->gearbox;
$car->price = $request->price;
$car->coinType = $request->coinType;
$car->save();
if ($files = $request->file('images')) {
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
}
foreach ($images as $imag) {
$image = new Image();
$image->car_id = $car->id;
$image->file_name = $imag;
$image->save();
}
return redirect()->route('cars.index')->with('success', 'Car saved !');
}
public function update(Request $request, $id)
{
$request->validate([
'model' => 'required',
'year' => 'required',
'color' => 'required',
'price'=> 'required',
'file_name.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$destionationPath = public_path('/images');
$images = [];
$car = Car::find($id);
$car->model = $request->model;
$car->seats = $request->seats;
$car->fuel = $request->fuel;
$car->year = $request->year;
$car->color = $request->color;
$car->gearbox = $request->gearbox;
$car->price = $request->price;
$car->coinType = $request->coinType;
$car->update();
if ($files = $request->file('images')) {
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
}
foreach ($images as $imag) {
//here I don't know what to do
}
return redirect()->route('cars.index')->with('success', 'Car updated !');
}
Thank you.
Looking at your blade file, you don't really show the original images, so the user can't update the images, he can insert new images and the old ones should be deleted, right?
If you want to update the image, you have to show the original images on the blade file with it's ID, so in the backend you can find the image based on the ID
But this should work for you now:
you can just check if the user uploaded any file
if ($files = $request->files('images')) {
...
delete all the old images
$car->images->each(function($image) {
// You probabily should be using Storage facade for this
// this should be the full path, I didn't test it, but if you need add extra methods so it returns the full path to the file
if (file_exists($destionationPath . '/' . $image->file_name) {
unset($destionationPath . '/' . $image->file_name);
}
$image->delete();
});
And then recreate the images like you do on store
foreach ($files as $file) {
$fileName = $file->getClientOriginalName();
$file->move($destionationPath, $fileName);
$images[] = $fileName;
}
foreach ($images as $imag) {
$image = new Image();
$image->car_id = $car->id;
$image->file_name = $imag;
$image->save();
}

Laravel $request value is null

I want to make dropdown menu where you choose company and it shows you owners that are in that company but when i request data from my blade.php in my controller i get NULL.
This is my blade.php
<form>
<label>Company:</label>
<select id="test" name="test" class="form-control input-sm">
#foreach($companies as $company)
<option value="{{$company->id}}">{{$company->name}}</option>
#endforeach
</select>
</form>
and this is my controller
public function index(Request $request)
{
$companies = Company::all();
$company_id = $request->get('company');
$owners = Owner::where('company_id',$company_id)->get();
return view ('owners', compact('owners','companies'));
}
and it's not showing any user but if I put any number manually like this
$company_id = 1;
then it shows owners from company where ID is 1.
UPDATE 2
My form looks like this now
<form action="{{ action('OwnerController#index') method="get"}}">
and my route is this
Route::get('owners', 'OwnerController#index');
Its still same.
Not sure what you want. But here is something for you.
File => create.blade.php
<form action='/item' method='POST'>
<label>Item Name:</label>
<input type="text" name="name" class="form-control input-sm">
<label>Company:</label>
<select id="company" name="company" class="form-control input-sm">
#foreach($companies as $company)
<option value="{{ $company->id }}">{{ $company->name }}</option>
#endforeach
</select>
<button class="btn btn-primary">Create</button>
</form>
File => ItemController.php
public function store(Request $request)
{
try {
$this->validate($request, [
'company_id' => 'required',
'name' => 'required|unique:items,name'
]);
$obj = new Item();
$obj->company_id = $request->input('company_id');
$obj->name = $request->input('name');
$obj->save();
return redirect()->route('item.index')
->with('success', 'Create Successful');
} catch (\Exception $ex) {
Log::error($ex->getMessage());
return redirect()->route('item.create')
->with('fail', $ex->getMessage());
}
}
As I said before I was missing some script. This solved my problem.
<form method="get" id="company_change">
<label for="company">Company:</label>
<select id="company" name="company" onchange="document.getElementById('company_change').submit()">
<option value="">----Select Company-----</option>
#foreach($companies as $company)
<option value="{{$company->id}}">{{$company->name}}</option>
#endforeach
</select>
</form>
My route is
Route::resource('owners', 'OwnerController');
You dont need a form to fill your dropdown;
You create a relationship in your model between Company and Owner and you dont even need a where,simply use eloquent like this
$owners = Owner::get();
And then in your view simply get the company using eloquent:
$owner->company->name;
That's it done!

Laravel 4 - Update many to many

I am currently trying to amend an update page which features a many to many relationship. It updates to my database perfectly, however all I'm trying to achieve now is to actually show the already selected items in my multiple select list in my view.
It currently just shows the entire list of oilgas jobs, just not the currently selected ones which should come from the query in some way.
So, it currently looks like this:
I need it to look like this, if Instrument Technician was previously chosen.
The associated files are as follows:
MODELS
OilGasJob.php
<?php
class OilGasJob extends \Eloquent {
protected $table = 'oilgasjobs';
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function oilgasjobs()
{
return $this->belongsToMany('OilGasJob');
}
}
CONTROLLER (CREATE PAGE AND STORE)
public function edit($id)
{
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit')->with('industryjob',$industryjob);
}
public function update($id)
{
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::back()->withErrors($validation);
} else {
$industryjob = IndustryJob::find($id);
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This divison job is not valid');
}
View::share('page_title', 'Edit Division Job');
$industryjob->job_title = Input::get('job_title');
$industryjob->slug = Str::slug(Input::get('job_title'));
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
$industryjob->oilgasjobs()->sync(Input::get('oilgasjobs'));
return Redirect::to('/admin/industry-jobs')->with('message', 'Division Job updated successfully');
}
}
VIEW
{{ Form::open(array('url' => URL::to('admin/industry-jobs/edit/'.$industryjob->id), 'class'=>'form-horizontal', 'method' => 'POST')) }}
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="{{ $industryjob->job_title }}" />
</div>
</div>
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Jobs in Oil & Gas</label>
<div class="col-md-10">
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<option value="{{ $oilgasjob->id }}" >{{ $oilgasjob->job_title }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Update Job</button>
</div>
</div>
<!-- ./ form actions -->
{{ Form::close() }}
In edit method add this code:
// ...
$linkedOilgasjob = DB::table('oilgasjob_industryjob')->lists('oilgasjob_id');
return View::make('admin/industry-jobs/edit'
,compact('industryjob')
,compact('linkedOilgasjob'));
Then in your view
<option value="{{ $oilgasjob->id }}" {{ in_array($oilgasjob->id,linkedOilgasjob) ? "selected='selected'" : "" }} >
{{ $oilgasjob->job_title }}
</option>
CONTROLLER
public function edit($id)
{
$data['industryjob'] = IndustryJob::find($id);
$data['oilgasjobs'] = DB::table('industry_job_oil_gas_job')->where('industry_job_id','=',$id)->lists('oil_gas_job_id');
if(is_null($id))
{
return Redirect::to('/admin/industry-jobs')->with('message', 'This division job is not valid');
}
View::share('page_title', 'Edit Division Job');
return View::make('admin/industry-jobs/edit', $data);
}
VIEW
<select name="oilgasjobs[]" id="oilgasjobs[]" size="6" class="form-control" multiple>
#foreach(OilGasJob::orderBy('job_title', 'ASC')->get() as $oilgasjob)
<?php
$selected = "";
if(in_array($oilgasjob->id, $oilgasjobs))
$selected = "selected";
?>
<option value="{{ $oilgasjob->id }}" <?php echo $selected; ?>>{{ $oilgasjob->job_title }}</option>
#endforeach
</select>

Resources