how to update values in Laravel 5.2 - php

I am going to update My permission table value.
this is controlller function
public function edit($project,$id)
{
$projectId=Project::findOrFail($project, ['id'])->id;
$permissions = Permission::permissioneditt($id,$projectId)->get();
view('collaborators.permissionedit')->withPermissions($permissions);
return view('collaborators.permissionedit', compact('permissions', 'projectId','collaborator->user()->first()->id'));
}
and this is update function
public function update(Request $request, $projectId, $collaboratorId)
{
$this->validate($request, [
'status' => 'required',
]);
DB::table('permissions')
->where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->update(['status' => $request->input('status')]);
return redirect()->back()->with('info','Your Permission has been updated successfully');
}
this is update form
<form class="form-vertical" role="form" method="post" action="{{url('projects/' .$projectId .'/collaborators/' . $collaboratorId.'}}">
<div class="form-group{{ $errors->has('status') ? ' has-error' : '' }}">
<label for="status" class="control-label">Choose Permission</label>
<select name="status" id="status">
<option value="{!! $permission->status !!}">{!! $permission->status !!}</option>
<option value="3">3</option>
<option value="2">2</option>
<option value="1">1</option>
{{ getStatus($permission->status) }}
</select>
#if ($errors->has('status'))
<span class="help-block">{{ $errors->first('status') }}</span>
#endif
{{-- {{$permission->project_id}} --}}
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Update</button>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{!! method_field('PUT') !!}
</form>
and this is routes
Route::put('projects/{projects}/collaborators/{id}',['uses'=>'ProjectCollaboratorsController#update',]);
but when I click update button it is generated following error
FatalErrorException in 607c064f09cf795b94deb14e18a3a34650c521d0.php line 23: syntax error, unexpected 'status' (T_STRING)
how can I fix this problem?

Related

Why did not update table columns values in Laravel 5.6?

in laravel 5.6 app I have table name as vehicles, then I need update some of table values in VehicleController update function as this,
public function update(Request $request, $id)
{
$vehicle = Vehicle::find($id);
$vehicle->provincename = $request->input('provincename');
$vehicle->districtname = $request->input('districtname');
$vehicle->townname = $request->input('townname');
$vehicle->brandname = $request->input('brandname');
$vehicle->modelname = $request->input('modelname');
$vehicle->modelyear = $request->input('year');
$vehicle->condition = $request->input('condition');
$vehicle->milage = $request->input('milage');
$vehicle->detail = $request->input('data');
$vehicle->price = $request->input('price');
$vehicle->telephone = $request->input('telephone');
$vehicle->categoryname = $request->input('categoryname');
$vehicle->transmission = $request->input('transmission');
$vehicle->fueltype = $request->input('fueltype');
$vehicle->enginecapacity = $request->input('enginecapacity');
$vehicle->user_id = Auth::user()->id;
$vehicle->save();
and edit form action is,
<form method="post" action="{{ route('vehicles.edit', [$vehicles->id]) }}" enctype="multipart/form-data">
and update route is,
Route::post('myads/{id}', [
'uses' => '\App\Http\Controllers\VehicleController#update',
])->name('vehicles.edit');
and controller edit function,
public function edit($id)
{
$vehicles = Vehicle::findOrFail($id);
}
and edit route is,
Route::get('myads/{id}/edit', [
'uses' => '\App\Http\Controllers\VehicleController#edit',
'as'=> 'vehicles.edit'
]);
but when I click update button it did not update values. no any error occurred here only redirect back to edit form. how can fix this problem?
vehicle model
class Vehicle extends Model
{
use Searchable;
protected $guarded = [];
public function searchableAs()
{
return 'categoryname';
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function uploads()
{
return $this->hasMany(Upload::class);
}
public function cars()
{
return $this->hasMany(Car::class);
}
public function vans()
{
return $this->hasMany(Car::class);
}
public function scopePersonal($query)
{
return $query->where('user_id', Auth::user()->id);
}
}
edit form is,
<form method="post" action="{{ route('vehicles.edit', [$vehicles->id]) }}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group{{ $errors->has('provincename') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Province</label>
<select name="provincename" id="provincename" class="form-control input dynamic" data-dependent="districtname" >
<option value="{{$vehicles->provincename}}">{!! $vehicles->provincename !!}</option>
#foreach($town_list as $town)
<option value="{{$town->provincename}}">{{$town->provincename}}</option>
#endforeach
</select>
#if ($errors->has('provincename'))
<span class="help-block">{{ $errors->first('provincename') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('districtname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">District</label>
<select name="districtname" id="districtname" class="form-control input dynamic" data-dependent="townname" >
<option value="{{$vehicles->districtname}}">{!! $vehicles->districtname !!}</option>
</select>
#if ($errors->has('districtname'))
<span class="help-block">{{ $errors->first('districtname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('townname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Town</label>
<select name="townname" id="townname" class="form-control input">
<option value="{{$vehicles->townname}}">{!! $vehicles->townname !!}</option>
</select>
#if ($errors->has('townname'))
<span class="help-block">{{ $errors->first('townname') }}</span>
#endif
</div>
<!--hidden select box-->
<div class="form-group" style="display: none;">
<label for="exampleFormControlSelect1">Vehicle Category</label>
<select name="categoryname" id="categoryname" class="form-control input dynamic" data-dependent="brandname" >
#foreach($model_list as $model)
<option value="{{$vehicles->categoryname}}">{{$vehicles->categoryname}}</option>
#endforeach
</select>
</div>
<div class="form-group{{ $errors->has('brandname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Brand</label>
<select name="brandname" id="brandname" class="form-control input dynamic" data-dependent="modelname" >
<option value="{{$vehicles->brandname}}">{!! $vehicles->brandname !!}</option>
</select>
#if ($errors->has('brandname'))
<span class="help-block">{{ $errors->first('brandname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('modelname') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Model</label>
<select name="modelname" id="modelname" class="form-control input">
<option value="{{$vehicles->modelname}}">{!! $vehicles->modelname !!}</option>
</select>
#if ($errors->has('modelname'))
<span class="help-block">{{ $errors->first('modelname') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('year') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Model Year</label>
<input type="text" class="form-control" id="year" placeholder="Year" name="year" value="{!! $vehicles->modelyear ?: '' !!}">
#if ($errors->has('year'))
<span class="help-block">{{ $errors->first('year') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('condition') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Condition</label>
<label class="radio-inline"><input type="radio" name="condition" value="used" #if($vehicles->condition == 'used') checked #endif>Used</label>
<label class="radio-inline"><input type="radio" name="condition" value="recondition" #if($vehicles->condition == 'recondition') checked #endif>Recondition</label>
<label class="radio-inline"><input type="radio" name="condition" value="new" #if($vehicles->condition == 'new') checked #endif> New</label>
#if ($errors->has('condition'))
<span class="help-block">{{ $errors->first('condition') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('milage') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Milage</label>
<input type="text" class="form-control" id="milage" placeholder="Milage" name="milage" value="{!! $vehicles->milage ?: '' !!}">
#if ($errors->has('milage'))
<span class="help-block">{{ $errors->first('milage') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('transmission') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Transmission</label>
<select class="form-control" id="transmission" name="transmission">
<option value="{!! $vehicles->transmission !!}">{!! $vehicles->transmission !!}</option>
<option value="Manual">Manual</option>
<option value="Auto">Auto</option>
<option value="Hybrid">Hybrid</option>
<option value="Electric">Electric</option>
<option value="Codak">codak</option>
</select>
#if ($errors->has('transmission'))
<span class="help-block">{{ $errors->first('transmission') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('fueltype') ? ' has-error' : '' }}">
<label for="exampleFormControlSelect1">Fuel Type</label>
<select class="form-control" id="fueltype" name="fueltype">
<option value="{!! $vehicles->fueltype !!}">{!! $vehicles->fueltype !!}</option>
<option value="Petrol">Petrol</option>
<option value="Diesel">Diesel</option>
<option value="Hybrid">Hybrid</option>
<option value="Electric">Electric</option>
</select>
#if ($errors->has('fueltype'))
<span class="help-block">{{ $errors->first('fueltype') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('enginecapacity') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Engine capacity</label>
<input type="text" class="form-control" id="enginecapacity" placeholder="Engine capacity" name="enginecapacity" value="{!! $vehicles->enginecapacity ?: '' !!}" >
#if ($errors->has('enginecapacity'))
<span class="help-block">{{ $errors->first('enginecapacity') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('data') ? ' has-error' : '' }}">
<label for="comment">More Details</label>
<textarea class="form-control" rows="5" id="data" name="data" rows="10" cols="10">{!! trim($vehicles->detail) !!}</textarea>
#if ($errors->has('data'))
<span class="help-block">{{ $errors->first('data') }}</span>
#endif
</div >
<div class="form-group{{ $errors->has('price') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Price</label>
<input type="text" class="form-control" id="price" placeholder="Price" name="price" value="{!! $vehicles->price ?: '' !!}">
#if ($errors->has('price'))
<span class="help-block">{{ $errors->first('price') }}</span>
#endif
</div>
<div class="form-group{{ $errors->has('telephone') ? ' has-error' : '' }}">
<label for="formGroupExampleInput">Telephone</label>
<input type="text" class="form-control" id="telephone" placeholder="Telephone" name="telephone" value="{!! $vehicles->telephone ?: '' !!}" >
#if ($errors->has('telephone'))
<span class="help-block">{{ $errors->first('telephone') }}</span>
#endif
</div>
<!-- <button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</div> -->
#if( $vehicles->uploads->count() > 0 )
#php
$upload = $vehicles->uploads->sortByDesc('id')->first();
#endphp
<!-- <img id="preview" src="/images/{{ $upload->resized_name }}"> -->
<!--edit/delete buttons-->
#foreach( $vehicles-> uploads as $upload)
<img id="preview"
src="{{asset((isset($upload) && $upload->resized_name!='')?'images/'.$upload->resized_name:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="files[]" type="file" id="files" name="_token" value="{{ csrf_token() }}" enctype="multipart/form-data">
<br/>
<!-- Add Image | -->
<!-- <a style="color: red" href="javascript:removeImage()">Delete</a>
<input type="hidden" style="display: none" value="0" name="remove" id="remove"> -->
Edit Image|
<a class="button is-outlined" href="/myads/{{$upload->id}}/delete" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>
<hr>
#endforeach
#endif
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</div>
There will be mutiple reasons
1. You are not passing the csrf token with form request.
2. There will be one or more input value missing and you have not show the error message in the validation.
3. Vehicle id not exist.
etc.
try this way
and remove or comment this lines below
//$vehicle->save();
$vehicle = array('provincename'=>$request->input('provincename'),
'districtname' => $request->input('districtname'),
'townname' => $request->input('townname'),
'brandname' => $request->input('brandname'),
'modelname' => $request->input('modelname'),
'modelyear' => $request->input('year'),
'condition' => $request->input('condition'),
'milage' => $request->input('milage'),
'detail' => $request->input('data'),
'price' => $request->input('price'),
'telephone' => $request->input('telephone'),
'categoryname' => $request->input('categoryname'),
'transmission' => $request->input('transmission'),
'fueltype' => $request->input('fueltype'),
'enginecapacity' => $request->input('enginecapacity'),
'user_id' => Auth::user()->id);
Vehicle::where('id', $id)->update($vehicle);
You can use array to update your record and also make sure to pass csrf token when submitting a data. Add user_id column to the array.
DB::table('vehicles')
->where('id', $vehicle)
->update(['provincename ' => $request->input('provincename'),
'districtname'=>$request->input('districtname'),
'townname' =>input('townname'), 'user_id'=>Auth::user()->id ]);

Adding data with multiple tables in one form many to many relationship in laravel 5.4

I am trying to insert with two tables with many to many relationship: Assignments and Collectors. I also make a intermediate or pivot table between them named assignment_collector.
create.blade.php in assignment folder
<form method="POST" action="{{ route('assignments.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="area_id">Area: </label>
<select class="form-control" name="area_id">
#foreach ($areas as $area)
<option value= "{{ $area->id }}">
{{ $area->campus }} {{ $area->building }} {{ $area->floor }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="mts_id">MTS: </label>
<select class="form-control" name="mts_id">
#foreach ($mts as $mt)
<option value= "{{ $mt->id }}">
{{ $mt->location }}
</option>
#endforeach
</select>
</div>
<div class="form-group">
<input type="hidden" class="form-control" id="status" name= "status" value="Active">
</div>
<div class="form-group">
<label for="collector_id">Collector: </label>
<select class="form-control" name="collector_id">
#foreach ($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<option value= "{{ $collector->id }}">
{{ $collector->firstname }} {{ $collector->lastname }}
</option>
#endforeach
#endforeach
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
AssignmentsController
public function store(Request $request)
{
$this->validate($request, [
'area_id' => 'required',
'mts_id' => 'required',
'status' => 'required',
'collector_id' => 'required'
]);
$assignment = new Assignment();
$assignment->area_id = $request->area_id;
$assignment->mts_id = $request->mts_id;
$assignment->status = $request->status;
$assignment->save();
$assignment_collector = new AssignmentCollector();
$assignment_collector->collector_id = $request->collector_id;
$assignment_collector->assignment_id = $assignment->id;
$assignment_collector->save();
return redirect('/assignments');
}
Assignment Model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector Model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
I got an error on this: App\AssignmentCollector since there is no AssignmentCollector and as I read the tutorials, you don't need to make a model for the pivot table. I reading the other articles but I get even more confused. Please help me because I'm still new in Laravel and I have get confused. Thanks!
You don't need a Model for your assignment collector table. What you want to do is create the Assignment then assign
$assignment->collectors()->create([
// all the collector data
]);

302 status is getting when submit form in laravel 5.5. After submit the form page is redirecting back

I have a form and inputs are inside loop. Each inputs are validating using Laravel validation array method. At present I am submitted name as name="guest[{{ $cart->_id }}][sleeps]" and name="guest[{{ $cart->_id }}][comments]". Validation is working fine for each input. But data is not submitted in to controller page. After submit page is redirect back. I am getting http 302 status. I have attached chrome console result. How can we submit data in to controller when I submit the form?
If I change name like name="sleeps[]" and name="comments[]" the data is posting in to controller. Any help would be appreciated.
routes.php
Route::post('/cart/store', 'CartController#store')->name('cart.store');
Html
<form action="{{ route('cart.store') }}" method="post">
{{ csrf_field() }}
<div class="panel panel-default text-left panel-booking1 panel-default-booking1">
#forelse($carts as $key => $cart)
<div class="col-sm-4 col-sm-4-booking1 form-group {{ $errors->has('guest.*.sleeps') ? ' has-error' : '' }}">
<label>Sleep(s)</label>
<select class="form-control form-control-booking1 jsBookCalSleep" name="guest[{{ $cart->_id }}][sleeps]">
<option value="">Choose Sleep(s)</option>
#for($i = 1; $i <= 30; $i++)
<option value="{{ $i }}" #if($i == $cart->sleeps) selected #endif>{{ $i }}</option>
#endfor
</select>
#if ($errors->has('guest.*.sleeps'))
<span class="help-block"><strong>{{ $errors->first('guest.*.sleeps') }}</strong></span>
#endif
</div>
<div class="col-sm-4 col-sm-4-f-booking1 comment-booking1 col-sm-4-booking1">
<div class="form-group {{ $errors->has($inputComments) ? ' has-error' : '' }}">
<textarea id="comments_{{ $cart->_id }}" name="guest[{{ $cart->_id }}][comments]" class="form-control" rows="3" maxlength="300" placeholder="Comment...">{{ old($inputComments) }}</textarea>
#if ($errors->has($inputComments))
<span class="help-block"><strong>{{ $errors->first($inputComments) }}</strong></span>
#endif
</div>
</div>
#empty
<p>No bookings in your cart</p>
#endforelse
<div>
<div id="btn-ground-2-booking1">
<button type="submit" class="btn btn-default-booking1 btn-default btn-sm btn-details btn-details-booking1"><span class="glyphicon glyphicon-credit-card" style="font-size: 14px;" aria-hidden="true"></span> Payment</button>
</div>
</div>
</form>
CartRequest.php
public function rules()
{
return [
'guest.*.sleeps' => 'required|not_in:0',
'guest.*.comments' => 'max:300',
];
}
CartController.php
public function store(CartRequest $request)
{
dd($request->all());
}
You can try:
public function rules()
{
$rules = [
'guest' => 'array'
];
foreach($this->request->get('guest') as $key => $val){
$rules['guest.'.$key.'. sleeps'] = 'required|not_in:0';
$rules['guest.'.$key.'. comments'] = 'max:300';
}
return $rules;
}
Hope it will help you.
302 is redirection code.do something like this
Route::post('/cart/store', 'CartController#store')->name('cart.store');
Replace the form tag by below line and check it.
<?php echo Form::open(['url' => '/cart/store', 'method' => 'post']); ?>

How to show categories in product creating page in Laravel

I have this form in the Laravel admin backend which adds new products to database.
productCreate.blade.php
{{ Form::open(['files' => true]) }}
<div class="form-group">
<label for="title" class="control-block">Product title:</label>
{{ Form::text('title', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
<label for="title" class="control-block">Product description:</label>
{{ Form::textarea('description', null, ['class' => 'form-control']) }}
<span class="help-block">HTML is allowed.</span>
</div>
<div class="form-group">
<label for="title" class="control-block">Product price:</label>
{{ Form::text('price', null, ['class' => 'form-control']) }}
</div>
<div class="form-group">
<label for="title" class="control-block">Assign Product to Category:</label>
<select class="form-control">
<option value="one">Category 1</option>
<option value="two">Category 2</option>
<option value="three">Category 3</option>
<option value="four">Category 4</option>
<option value="five">Category 5</option>
</select>
</div>
<div class="form-group">
<label for="title" class="control-block">Product image:</label>
{{ Form::file('image', ['class' => 'form-control']) }}
</div>
<hr />
<button type="submit" class="btn btn-primary">Create new product</button>
{{ Form::close() }}
My question is how to show this select/options values from database. I want to be able to assign products to categories. Where I should make query and how to add them here in the view?
In admincontroller i have functions for product creation which load the view
public function productsCreate() {
return View::make('site.admin.products_create');
}
and I tried to make it like this
public function productsCreate() {
$categories = Categories::paginate(15);
return View::make('site.admin.products_create', [
'categories' => $categories
]);
//return View::make('site.admin.products_create');
}
but then I got message
production.ERROR: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Cannot redeclare AdminController::productsCreate() ...
So how exactly I can query database table categories and show categories in the form?
May be because I already have categories selection in admin controller?
public function categories() {
$categories = Categories::all();
return View::make('site.admin.categories', [
'categories' => $categories
]);
}
public function productsCreate() {
// $categories = Categories::paginate(15);
return View::make('site.admin.products_create', [
'categories' => $categories
]);
//return View::make('site.admin.products_create');
}
You pass the categories in theproductsCreate function, and you must remove the old productsCreate function, you declared it twice :
public function productsCreate() {
$categories = Categories::get();
return View::make('site.admin.products_create', [
'categories' => $categories
]);
}
For the html :
<div class="form-group">
<label for="title" class="control-block">Assign Product to Category:</label>
<select class="form-control">
#foreach($categories as $categorie)
<option value="{{ $categorie->id }}">{{ $categorie->name }}</option>
#endforeach
</select>
I hope that will help you.

Highlight multiple select options after validations fails - Laravel 5.2

I'm learning Laravel 5.2 for first time, and I need to repopulate a form when the validation fails.
I was able to do so with single inputs as 'name' or 'description', but I couln't find out how to do it with the 'category' which is a multiple select.
View:
<form action="{{ url('addproduct') }}" method="POST">
{!! csrf_field() !!}
<div class="form-group">
<label for="#productName">Name:</label>
<input id="productName" class="form-control" name="name" type="text" placeholder="Product name" value="{{ old('name') }}">
</div>
<div class="form-group">
<label for="#productDescription">Description:</label>
<textarea id="productDescription" class="form-control" name="description" rows="3" placeholder="Product description" value="{{ old('description') }}"></textarea>
</div>
#if ($categories)
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<label for="#productQuantity">Quantity:</label>
<input id="productQuantity" class="form-control" name="quantity" type="number" min="0" value="0">
</div>
<button class="form-control btn btn-success" type="submit">Add Product</button>
</form>
Controller:
public function add(Request $request) {
$data = array();
$data['msgAdded'] = false;
$data['categories'] = Category::select('name', 'id')->get();
if ($request->isMethod('post')) {
$this->validate($request, [
'name' => 'required|max:50',
'description' => 'required|max:200',
'category' => 'required',
'quantity' => 'required|min:0',
]);
$product = new Product;
$product->name = $request->name;
$product->description = $request->description;
$product->quantity = $request->quantity;
$product->save();
foreach ($request->category as $cat) {
$category = Category::find($cat);
$category->products()->attach($product->id);
}
$data['msgAdded'] = true;
}
$data['view'] = 'addproduct';
return view('products/add', $data);
}
I would like to know if it can be achieve with blade, or the best way to achieve that.
Thank you!
Option 1
You would have to write the select part of your form like this:
<div class="form-group">
<label for="#productCategory">Category:</label>
<select id="productCategory" class="form-control" name="category[]" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}"{{ !empty(old('category')) && in_array($category->id, old('category')) ? ' selected="selected"' : '' }}>{{ $category->name }}</option>
#endforeach
</select>
</div>
Option 2
And arguably the more elegant solution is to install the html package from the laravel collective
composer require laravelcollective/html
follow the installation instructions on the laravel collective Forms & HTML documentation.
then just enter this where your select would be:
{!! Form::select('category[]', $categories, old('category'),['class' => 'form-control', 'multiple' => 'multiple'] ) !!}

Categories