Laravel Request Input is not usable data - laravel

Ok maybe this is a noob laravel question but when I'm trying to store data from a form I used a $request->input in a query to get a needed field for insert but the query will not run. Note: does run if I just set something like $project_id = 6.
public function store(Request $request)
{
$project_id = $request->input('project_id');
$company = Project::where('id', $project_id)->first();
if(Auth::check()){
$task = Task::create([
'name' => $request->input('name'),
'project_id' => $project_id,
'company_id' => $company->id,
'days' => $request->input('days'),
'hours' => $request->input('hours'),
'user_id' => Auth::user()->id
]);
if($task){
return redirect()->route('tasks.index')
->with('success' , 'Task created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new task');
}
Note:
I've tried a couple different things I've found online like $project_id = $request->project_id or $project_id = $request['project_id']
Is request->input just used for inserts and can't be used as a normal varible?
Update: here is the create.blade form it's coming from
#extends('layouts.app')
#section('content')
<div class="row col-md-9 col-lg-9 col-sm-9 pull-left " >
<h1>Add a Task </h1>
<!-- Example row of columns -->
<div class="col-md-12 col-lg-12 col-sm-12" style="background: white; margin: 10px;" >
<form method="post" action="{{ route('tasks.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="project-name">Name<span class="required">*</span></label>
<input placeholder="Enter name"
id="project-name"
required
name="name"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-days">Days Taken<span class="required"></span></label>
<input
id="task-days"
required
name="days"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-hours">Hours Taken<span class="required"></span></label>
<input
id="task-hours"
required
name="hours"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<input
class="form-control"
type="hidden"
name="project_id"
value="{{ $project_id }}"
/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{$project_id}}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit"/>
</div>
</form>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 col-sm-3 pull-right">
<div class="sidebar-module sidebar-module-inset">
<h4>Actions</h4>
<ol class="list-unstyled">
<li>All tasks</li>
</ol>
</div>
</div>
#endsection

Let's examine your <form> below:
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project_id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
In this code, you have a hidden input with the name "project_id", and if $projects is not null, you also have a select with the name "project_id". Having multiple elements with the same name is invalid, and can cause issues.
Secondly, in this line:
<option value="{{ $project_id }}">{{ $project->name }}</option>
$project_id is the same value you have in the hidden input above. When you're looping over $projects, this should be $project->id:
<option value="{{ $project->id }}">{{ $project->name }}</option>
Lastly, make sure that $project_id is a valid value if you're going to send it, and consider adjusting your logic to only send the hidden input if $projects is null:
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#else
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#endif
With all that adjusted, you should be able to retrieve the expected value with $request->input("project_id")

Related

Cannot find errors returned by validate method

I am using the validate method to validate user input and when I post a form with errors, I get redirected to the previous page but the form is not repopulated and the errors are not showing. I have include a partial view for showing errors in the page with the form. The partial view is:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
the action method in the controller is:
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'age' => 'required',
'product_code' => 'required|alpha_num',
'price' => 'required|numeric',
]);
$product=new Product();
The view with the form is:
#section('content')
<div class="container">
#include('partials.errors')
<form action="/products/create" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
#csrf
<div class="form-group">
<label>Product Name</label>
<input name="product_name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Age</label>
<input name="age" type="text" class="form-control">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control" name="gender">
<option>
Male
</option>
<option>
Female
</option>
Unisex
</option>
</select>
</div>
<div class="form-group">
<label>Product Code</label>
<input name="product_code" type="text" class="form-control">
</div>
<div class="form-group">
<label>Price</label>
<input name="price" type="text" class="form-control">
</div>
<div class="form-group">
<label>Product Category</label>
<select class="form-control" name="category_name">
#foreach ($product_categories as $product_category)
<option>{{ $product_category->category_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" name="brand_name">
#foreach ($brands as $brand)
<option>{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
</div>
#endsection
when I post a failed form, I get redirected to the view with the form but the form is not repopulated with the input that I entered. additionally, the erros are not shown but just an empty red div. According to a book I read, if the data isn’t valid, the validate method throws a ValidationException and the exception will return a redirect to the previous page, together with all of the user input and the validation errors. I am new to laravel.
You should use old() method to keep repopulate entered value in input field like below
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
To show validation error you have to add errors in each field for example like below
#error("product_code")
<div class="invalid-feedback">{{ $message }}</div>
#enderror
You can read more about old method here
https://laravel.com/docs/8.x/requests#retrieving-old-input
For validation error
https://laravel.com/docs/8.x/validation#the-at-error-directive
First, the CSRF token:
If you check the docs you'll see that you have 2 options how to add it:
#csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
You are doing both, remove one of them.
Second, the old input:
You are missing the old input call. For example:
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
Last, the errors:
You are doing it correctly.
If is still not working, check that your route is using the middleware web.

Laravel Error during update - Undefined variable: id

I am working on a project using Laravel-5.8
protected $table = 'ratings';
protected $fillable = [
'rating_type',
'rating_value',
'rating_description',
];
public function rules()
{
return [
'rating_type' => 'required|numeric|min:1|max:10|unique:appraisal_ratings,rating_type,company_id'.$this->id,
];
}
The rating has an id column, and that's the primary key. Why I checked it against company_id is that different companies can have the same rating type.
Controller
public function edit($id)
{
$rating = Rating::where('id', $id)->first();
return view('ratings.edit')
->with('rating', $rating)
->with('rating_types', $this->rating_types)
->with('rating_descriptions', $this->rating_descriptions)
->with('rating_values', $this->rating_values);
}
public function update(UpdateRatingRequest $request, $id)
{
$rating = Rating::find($id);
$rating->rating_type = $request->rating_type;
$rating->rating_value = $request->rating_value;
$rating->rating_description = $request->rating_description;
$rating->save();
Session::flash('success', 'Rating is updated successfully');
return redirect()->route('ratings.index');
}
edit.blade
<form action="{{route('ratings.update', ['id'=>$rating->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<input name="_method" type="hidden" value="PUT">
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating" tabindex="1" name="rating_type" style="width: 100%;">
<option value="">Select Rating</option>
#foreach($rating_types as $k => $rating_type)
<option value="{{$k}}" #if($rating->rating_type == $k) selected #endif>{{$rating_type}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Description:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Description" tabindex="1" name="rating_description" style="width: 100%;">
<option value="">Select Description</option>
#foreach($rating_descriptions as $k => $rating_description)
<option value="{{$k}}" #if($rating->rating_description == $k) selected #endif>{{$rating_description}}</option>
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Rating Score:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Rating Score" tabindex="1" name="rating_value" style="width: 100%;">
<option value="">Select Rating Score</option>
#foreach($rating_values as $k => $rating_value)
<option value="{{$k}}" #if($rating->rating_value == $k) selected #endif>{{$rating_value}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('ratings.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
When I clicked on the save button to update, I got this error:
rating_type already exists.
That error should not have occured since I am doing update.
How do I resolve it?
Thank you.
You are checking the unique on update wrong
Unique Rule Usage
unique:table,column,except,idColumn
* 3rd param is for value for column to except and 4th is for column to except
Fix
//App\Http\Requests\UpdateRatingRequest
'rating_type' => 'required|numeric|min:1|max:10|unique:table_name,rating_type,table_primary_key'.$this->id,

when click submit error is occur

when click on submit data,data successfully save and show in database but got error in index page, i think don't get it user-id
Trying to get property 'id' of non-object (View:
C:\xampp\htdocs\ytl\resources\views\profile\index.blade.php)
This is index.blade.php file
<form method="post", id="form", action="{{action('Profile\UserProfileController#index')}}" accept-charset="UTF-8">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6 mb-3 form-group">
Exchange:<select name="exchange_id" id="exchange" class="form-control " onchange="myfunc()">
<option value="">Select</option>
#foreach($exchanges as $key=>$val )
<option value="{{ $val->id }}">{{ $val->exchange }}</option>
#endforeach
</select>
{{--{!! Form::label('exchange_id', 'Exchanges: ') !!}--}}
{{--{!! Form::select('exchange_id', ['' => 'Choose Options'] + $exchanges, null, ['class' => 'form-control', 'id' => 'exchange', 'name' => 'exchange_id'])!!}--}}
</div>
<div class="col-md-6 mb-3 form-group">
Market<select name="market_id" id="market" class="form-control bindselect" >
<option value="">Select</option>
{{--#foreach($markets as $key=>$val )--}}
{{--<option value="{{ $val->id }}">{{ $val->market }}</option>--}}
{{--#endforeach--}}
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Country:<select name="country_id" id="country" class="form-control " >
<option value="">Select</option>
#foreach($countries as $key=>$val )
<option value="{{ $val->id }}">{{ $val->country }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
Company:<select name="brokerage_company_id" id="brokerage_company_id" class="form-control " >
<option value="">Select</option>
#foreach($brokerage_company as $key=>$val )
<option value="{{ $val->id }}">{{ $val->brokerage_company }}</option>
#endforeach
</select>
</div>
<div class="col-md-6 mb-3 form-group">
{{--{!! Form::label('Intraday_Charge', 'Intraday Charge:') !!}--}}
{{--{!! Form::text('Intraday_Charge', null, ['required' => 'required', 'class'=>'form-control number_only'])!!}--}}
Intraday_charge: <input type="text" name="charge_intraday" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_delivery" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_lot" class="form-control"><br>
</div>
<div class="col-md-6 mb-3 form-group">
Delivery_charge: <input type="text" name="charge_per_order" class="form-control"><br>
</div>
<div class="mb-3 form-group">
{{--{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}--}}
<input type="submit" value="Submit">
</div>
</div>
</form>
This is controller in which 2 method. 1st index and 2nd store method
public function index(Request $request){
$exchanges = Exchange::select('exchange','id')->get();
$markets = Market::select('market','id')->get();
$countries = Country::select('country','id')->get();
$brokerage_company = BrokerageCompany::select('brokerage_company','id')->get();
return view('profile.index', compact( 'exchanges','markets','countries','brokerage_company'));
}
public function store(Request $request){
$Input = $request->all();
$user = Auth::user();
$user->userprofile()->create($Input);
$user_id = Auth::user()->id;
$exchanges = Exchange::pluck('exchange','id')->all();
$markets = Market::pluck('market','id')->all();
$countries = Country::pluck('country','id')->all();
$brokerage = BrokerageCompany::pluck('brokerage_company','id')->all();
$user_profile = UserProfile::pluck('charge_intraday','charge_delivery','charge_per_lot','charge_per_order');
return view('profile.index', compact( 'exchanges','markets','countries','brokerage','user_profile'));
}
Since Laravel 5.2 pluck() method of Eloquent builder returns a collection of values from given column. When you call all() on this collection, you simply get an array of values from that first column. For example, when you call
$exchanges = Exchange::pluck('exchange','id')->all();
$exchanges will be an array that contains all values of exchange column in your Exchanges table. Hence the error, as you're trying to access id attribute of this scalar value.
I guess you're trying to limit number of columns fetched from the database. Call select() method instead of pluck():
$exchanges = Exchange::select('exchange','id')->get();

How to display selected tags in select option value in laravel?

This is my Post Create View
<div class="col-lg-12">
<form action="{{ route('admin.post.store') }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ old('title') }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ old('body') }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-success btn-block">Publish</button>
</form>
</div>
Tags have many to many relationship.
Here I can select many tags, but in the post edit view I cant see the selected tags that selected by me in the post create view.
I want to show selected tags in select option value and edit theme.
post update methods:
public function edit(Post $post)
{
$tags = Tag::all()->pluck('name', 'id');
$cats = Category::all();
return view('admin.post.edit', compact(['post', 'cats', 'tags']));
}
public function update(Post $post, Request $request)
{
$this->validate($request, [
'title' => 'required|min:3|max:255',
'slug' => 'nullable|string',
'image' => 'sometimes|mimes:jpeg,bmp,png,jpg,gif',
'body' => 'required',
'category' => 'nullable',
'views' => 'nullable',
'tags' => 'nullable',
]);
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->category_id = $request->category;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldfilename = $post->image;
$post->image = $filename;
Storage::delete($oldfilename);
}
$post->save();
$post->tags()->sync($request->tags, false);
Session::flash('update', 'Post Updated Successfully');
return redirect()->route('admin.post.index');
}
post edit view:
<div class="col-lg-12">
<form action="{{ route('admin.post.update',$post->id) }}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
{{ method_field('patch') }}
<div class="form-group">
<label for="title">Post Title</label>
<input type="text" class="form-control" value="{{ $post->title }}" name="title" id="title"
placeholder="Enter Post Title">
<span class="text-danger">{{ $errors->first('title') }}</span>
</div>
<div class="form-group">
<label for="slug">Post Image</label>
<input type="file" class="form-control" name="image" id="image"
placeholder="Select Post Image">
<span class="text-danger">{{ $errors->first('image') }}</span>
</div>
<div class="form-group">
<label for="tags">Select Tags</label>
<select class="js-example-basic-single form-control" name="tags[]" id="tags" multiple="multiple">
</select>
</div>
<div class="form-group">
<textarea class="body" name="body">{{ $post->body }}</textarea>
<span class="text-danger">{{ $errors->first('body') }}</span>
</div>
<div class="form-group">
<label for="category">Select Category</label>
<select class="form-control" name="category" id="category">
<option value="">Select</option>
#foreach($cats as $cat)
<option <?php if ($cat->id == $post->category_id) {
echo 'selected';
} ?> value="{{ $cat->id }}">{{ $cat->name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary btn-block">Edit</button>
</form>
</div>
here:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}">{{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}</option>
#endforeach
</select>
</div>
how can I pass selected post tags from database and show theme here and edit them.
I am using select2 plugin
In select2 I should pass data in jQuery:
$('.js-example-basic-single').select2().val({{ json_decode($post->tags()->getRelatedIds()) }}).trigger('change');
but it doesnt work :(
and I get this error
Method Illuminate\Database\Query\Builder::getRelatedIds does not exist. (View: C:\Users\M0RT3Z4\Desktop\MyBlog\resources\views\admin\post\edit.blade.php
Please help me, Thanks!
You have put the code in wrong place:
Try this:
<div class="form-group">
<label for="tags">Select Tags</label>
<select multiple class="form-control" name="tags[]" id="tags">
#foreach($tags as $id => $name)
<option id="{{ $id }}" {{ in_array($id,$post->category()->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $name }}</option>
#endforeach
</select>
</div>

Laravel 5.3 - 500 internal error when saving a new Eloquent model

When trying to create a new instance of my model Apartment I get a 500 (Internal Server Error). I have other /create/ routes that I use to create new instance of my models and they work properly and they're set up same as ApartmentController#create, but for some weird reason it doesn't work.
ApartmentController#create
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$addresses = Address::all();
return view('address/create')->with('addresses', $addresses);
}
ApartmentController#store
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$address = new Address();
$this->authorize('create', $address);
$validator = Validator::make($request->all(), [
'building_number' => 'required|integer',
'street' => 'required|string',
]);
if ($validator->fails()) {
return redirect('addresses/create')
->withErrors($validator)
->withInput();
}
$address->building_number = $request->building_number;
$address->street = $request->street;
$address->save();
return redirect('addresses/create');
}
View apartment/create
<div class="col-md-6">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form-horizontal" method="POST" action="{{ action("ApartmentController#store") }}">
<fieldset>
<!-- Form Name -->
<legend>Register a new apartment</legend>
{{ csrf_field() }}
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="address_id">Address</label>
<div class="col-md-4">
<select id="address_id" name="address_id" class="form-control">
#foreach($addresses as $address)
<option value="{{$address->id}}">{{$address->street}} {{$address->building_number}}</option>
#endforeach
</select>
<span class="help-block">Apartments building number</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="apartment_number">Apartment Number</label>
<div class="col-md-4">
<input id="apartment_number" name="apartment_number" type="text" placeholder="2402" class="form-control input-md" required="">
<span class="help-block">The apartment number</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="size">Apartment Size</label>
<div class="col-md-4">
<input id="size" name="size" type="text" placeholder="56qm" class="form-control input-md" required="">
<span class="help-block">The size of the apartment in qm</span>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="living_area_size">Living Area Size</label>
<div class="col-md-4">
<input id="living_area_size" name="living_area_size" type="text" placeholder="23qm" class="form-control input-md" required="">
<span class="help-block">The size of the living area in qm</span>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="suitable_for">Suitable For</label>
<div class="col-md-4">
<select id="suitable_for" name="suitable_for" class="form-control">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<span class="help-block">Number of people the apartment is suitable for.</span>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="furnished">Furnished</label>
<div class="col-md-4">
<select id="furnished" name="furnished" class="form-control">
<option value="1">Yes</option>
<option value="0">No</option>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="balcony_or_terrace">Balcony or Terrace</label>
<div class="col-md-4">
<select id="balcony_or_terrace" name="balcony_or_terrace" class="form-control">
<option value="none">None</option>
<option value="balcony">Balcony</option>
<option value="terrace">Terrace</option>
</select>
</div>
</div>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="floor">Floor</label>
<div class="col-md-4">
<select id="floor" name="floor" class="form-control">
<option value="ground">Ground</option>
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Description</label>
<div class="col-md-6">
<textarea class="form-control" id="description" name="description"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" name="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
<div class="col-md-4">
<legend>Registered Apartments</legend>
#foreach($apartments as $apartment)
<div class="address">
Apartment {{ $apartment->apartment_number }}
<a href="{{ url('/apartments/' . $apartment->id . '/edit') }}"
onclick="event.preventDefault();
document.getElementById('edit-form-{{$apartment->id}}').submit();">
<button class="btn btn-default">Edit</button>
</a>
<form id="edit-form-{{$apartment->id}}" action="{{ url('/apartments/' . $apartment->id . '/edit') }}" method="GET" style="display: none;">
{{ csrf_field() }}
<input type="hidden" name="address_id" value="{{$apartment->id}}">
</form>
<a href="{{ url('/apartments/' . $apartment->id) }}"
onclick="event.preventDefault();
document.getElementById('delete-form-{{$apartment->id}}').submit();">
<button class="btn btn-warning">Delete</button>
</a>
<form id="delete-form-{{$apartment->id}}" method="POST" action="/apartments/{{$apartment->id}}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
</form>
</div>
<br>
#endforeach
</div>
Route web.php
Route::resource('apartments', 'ApartmentController');
apartments table for Apartment model
I tried to catch the exception on the save() method, but nothing is being caught and I still get redirected to /apartments without any Laravel error just Chroms 500 error page.
This is how I tried to catch the error using dwightwatson/validating:
try{
$apartment = new Apartment();
$apartment->apartment_number = $request->apartment_number;
$apartment->size = $request->size;
$apartment->living_area_size = $request->living_area_size;
$apartment->suitable_for = $request->suitable_for;
$apartment->furnished = $request->furnished;
$apartment->balcony_or_terrace = $request->balcony_or_terrace;
$apartment->floor = $request->floor;
$apartment->description = $request->description;
$apartment->address_id = $request->address_id;
$apartment->saveOrFail();
} catch (ValidationException $e) {
$errors = $e->getErrors();
return redirect()->route('apartments.create')
->withErrors($errors)
->withInput();
}
First of all, you Download Fiddler if you haven't already. Fire it up and then trigger the store method again. Fiddler should tell you a great deal about your request and response:
On the left side, you have a list of requests and on the right, you have statistics and inspectors. Under inspectors tab you will see WebView. Click it and you will see the error generated by Laravel.
As for why it might be failing, check if the references are included properly. e.g:
use App\Address;

Resources