Laravel a form isn't reset after successful submit - laravel

This is my controller:
class GuestbookController extends Controller
{
public function viewAll(Request $request)
{
if ($request->method() === 'POST') {
$this->validate($request, [
'username' => 'required|string|regex:/^[a-zA-Z\d]+$/',
'email' => 'required|string|email',
'homepage' => 'nullable|string|url',
'text' => 'string',
'captcha' => 'required|captcha',
],
[
'captcha.captcha' => 'The captcha is incorrect',
'username.regex' => 'Use English letters and digits only',
]);
$message = new Message();
$message->username = $request->get('username');
$message->email = $request->get('email');
$message->homepage = $request->get('homepage');
$message->text = strip_tags($request->get('text'));
$message->ip = $request->ip();
$message->browser = get_browser($request->header('User-Agent'))->browser;
$message->save();
}
$messages = Message::sortable(['created_at' => 'desc'])->paginate(25);
return view('Guestbook.viewAll', [
'newMessage' => new Message(),
'messages' => $messages
]);
}
}
I am using this plugin. viewAll handles both GET and POST requests, but the problem is that the form isn't reset when I successfully submit data keeping all the previous input values.
I've checked what the server sends and it seems like it sends inputs with last values in them. I've no idea what to do, please help!
View:
#extends('base')
#section('title', 'Guestbook')
#section('baseContent')
{!! BootForm::open(['model' => $newMessage]) !!}
{!! BootForm::text('username') !!}
{!! BootForm::email('email') !!}
{!! BootForm::text('homepage') !!}
{!! BootForm::textarea('text') !!}
{!! captcha_img() !!}
{!! BootForm::text('captcha') !!}
{!! BootForm::submit('Send') !!}
{!! BootForm::close() !!}
#if (count($messages) > 0)
<table class="table table-bordered">
<tr>
<td>#sortablelink('username', 'Username')</td>
<td>#sortablelink('email', 'Email')</td>
<td>Homepage</td>
<td>#sortablelink('created_at', 'Data added')</td>
<td>Message</td>
</tr>
#foreach ($messages as $message)
<tr>
<td>{{ $message->username }}</td>
<td>{{ $message->email }}</td>
<td>{{ $message->homepage }}</td>
<td>{{ $message->created_at }}</td>
<td>{{ $message->message }}</td>
</tr>
#endforeach
</table>
#else
There is nothing to display here.
#endif
{!! $messages->appends(\Request::except('page'))->render() !!}
#endsection
See all code here.

BootForm is compiled like this
<div class="form-group">
<label for="username" class="control-label col-md-2">Username</label>
<div class="col-md-10">
<input type="text" value={{old('username')}} name="username" class="form-control">
</div>
The old('params') is a helper method which keeps the previous inputs in session. And secondly, you have model associated with it.
I hope this helps

Related

how to Checked if value of static checkboxes are equal on what you have in your database in Laravel

I have this column in my database named "source_income"
Which was Imploded from my EDIT page.
Problem is after I save the record, I see all the checkboxes are checked. I understand that the cause of the problem is that I do not have something that will check if the value of the checkbox should be equal to what I have in the database.
The checkboxes on my form are not dynamic.
<div class="col-md-6 ">
<div class="form-group {{ $errors->has('source_income') ? 'has-error' : ''}}">
<strong>Check all that apply to you:</strong>
<br>
<br>
{!! Form::checkbox('source_income[]', 'employed', null, ['id' => 'employed']) !!}
{!! Form::label('employed', 'Employed') !!}
<br>
{!! Form::checkbox('source_income[]', 'online-seller', null, ['id' => 'online-seller']) !!}
{!! Form::label('online-seller', 'Online Seller') !!}
<br>
{!! Form::checkbox('source_income[]', 'rider', null, ['id' => 'rider']) !!}
{!! Form::label('rider', 'Rider (Grab,Lazada,Etc.)') !!}
<br>
{!! Form::checkbox('source_income[]', 'small-business-owner', null, ['id' => 'small-business-owner']) !!}
{!! Form::label('small-business-owner', 'Small Business Owner') !!}
<br>
{!! Form::checkbox('source_income[]', 'no-income', null, ['id' => 'no-income']) !!}
{!! Form::label('no-income', 'No income') !!}
<br>
{!! Form::checkbox('source_income[]', 'remittances-allotment', null, ['id' => 'remittances-allotment']) !!}
{!! Form::label('remittances-allotment', 'Remittances / Allotment') !!}
{!! $errors->first('source_income', '<p class="help-block">:message</p>') !!}
</div>
</div>
EDIT,BLADE.PHP
public function edit($id, Profile $model)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$profile = Profile::findOrFail($id);
$profileSourceIncome = explode(",", $profile->source_income);
return view('dashboard.profile.edit', compact('model','profile'))
->with('user', $user)
->with('profileSourceIncome', $profileSourceIncome);
}
I literally stopped in this part $profileSourceIncome = explode(",", $profile->source_income);
My question is how can I able to display the checkboxes checked if the name of the checkbox is equal to any value from $profileSourceIncome[]?
Thank you so much in advance!
According to the documentation, you only need to pass true as the third parameter in your Form::checkbox(...) calls to return a checkbox that is already checked.
public function edit($id, Profile $model)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$profile = Profile::findOrFail($id);
// Turn this array into a Collection
$profileSourceIncome = collect(explode(',', $profile->source_income));
return view('dashboard.profile.edit', compact('model','profile'))
->with('user', $user)
->with('profileSourceIncome', $profileSourceIncome);
}
And then, in your blade file, you could use the Collection's contains() method to do the following:
Form::checkbox('source_income[]', 'employed', $profileSourceIncome->contains('employed'), ['id' => 'employed'])
Form::checkbox('source_income[]', 'online-seller', $profileSourceIncome->contains('online-seller'), ['id' => 'online-seller'])
Form::checkbox('source_income[]', 'rider', $profileSourceIncome->contains('rider'), ['id' => 'rider'])
Form::checkbox('source_income[]', 'small-business-owner', $profileSourceIncome->contains('small-business-owner'), ['id' => 'business-owner'])
Form::checkbox('source_income[]', 'no-income', $profileSourceIncome->contains('no-income'), ['id' => 'no-income'])
Form::checkbox('source_income[]', 'remittances-allotment', $profileSourceIncome->contains('remittances-allotment'), ['id' => 'remittances-allotment'])

Storing data from 1 table to another tables in laravel

I am pretty new to Laravel. I have a Table named Leads and Three other tables named Contacts, Companies, and Opportunities.
What I am trying to do is extract the data from the Leads table to these 3 other tables. Something like this : https://imgur.com/EZGqNQH . The way I want to achieve this is kind of like this: When the user clicked the 'Convert Lead' button, a modal will appear like this: https://imgur.com/EDgVR7U and if the user ticked the checkbox button for the Convert to Opportunity, an extra field will appear for the user to fill in: https://imgur.com/mrypfCC
I have made the necessary files for the process (maybe)
LeadController:
{
return view('leads.create')
->withUsers($this->users->getAllUsersWithDepartments())
->withClients($this->clients->listAllClients())
->withIndustries($this->clients->listAllIndustries())
->withLeadSource($this->leads->listAllSources());
}
public function convertLeads($id)
{
$lead = Lead::findOrFail($id);
$company = new Companies;
$opportunity = new Opportunity;
$contact = new Contact;
$company->lead_id = $lead->id;
$company->name = $lead->company_name;
$company->phone = $lead->company_phone;
$company->email = $lead->company_mail;
$company->address1 = $lead->company_address1;
$company->address2 = $lead->company_address2;
$company->state = $lead->company_state;
$company->zipcode = $lead->company_zipcode;
$company->city = $lead->company_city;
$company->country = $lead->company_country;
$company->save();
$contact->name = $lead->lead_name;
$contact->job_title = $lead->position;
$contact->email = $lead->mail;
$contact->primary_number = $lead->lead_phone;
$contact->description = $lead->description;
$contact->client_id = $lead->client_id;
$contact->save();
Session()->flash('flash_message', 'Lead successfully converted!');
return view('leads.show');
}
/**
* Store a newly created resource in storage.
*
* #param StoreLeadRequest|Request $request
*
* #return \Illuminate\Http\Response
*/
public function store(StoreLeadRequest $request)
{
$getInsertedId = $this->leads->create($request);
Session()->flash('flash_message', 'Lead is created');
return redirect()->route('leads.show', $getInsertedId);
}
public function show($id)
{
return view('leads.show')
->withLead($this->leads->find($id))
->withUsers($this->users->getAllUsersWithDepartments())
->withCompanyname($this->settings->getCompanyName());
}
Route:
Route::get('/data', 'LeadsController#anyData')->name('leads.data');
Route::get('/create', 'LeadsController#create')->name('leads.create');
Route::get('/show/{id}', 'LeadsController#show')->name('leads.show');
Route::get('convertLeads/{id}', 'LeadsController#convertLeads')->name('leads.convertLeads');
Route::get('/my', 'LeadsController#my')->name('leads.my');
Route::get('/mydata', 'LeadsController#myData')->name('leads.mydata');
Route::patch('/updateassign/{id}', 'LeadsController#updateAssign');
Route::patch('/updatestatus/{id}', 'LeadsController#updateStatus');
Route::patch('/updatefollowup/{id}', 'LeadsController#updateFollowup')->name('leads.followup');
});
Route::resource('leads', 'LeadsController');
Route::post('/comments/{type}/{id}', 'CommentController#store');
Views:
<div>
<table width="100%">
<tr>
<th></th>
</tr>
<tr>
{!!Form::open(array('route' => array('leads.convertLeads', $lead->id)))!!}
<td><li>Convert to Contact</li></td>
</tr>
<tr>
<td><li>Convert to Company</li></td>
</tr>
<tr>
<td><label for="chkOpportunity">
<input type="checkbox" id="chkOpportunity" />
Convert to Opportunity
</label>
<div id="dvOpportunity" style="display: none">
{!! Form::label('name', __('Lead Name'), ['class' => 'control-label']) !!}
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Value'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Type'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group" style="padding:5px">
{!! Form::label('country', __('Stage'), ['class' => 'control-label']) !!}
{!! Form::text('company_country', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
</div>
</div>
</td>
</tr>
</table>
<div class="modal-footer" style="margin:-13px; margin-top:4px;">
<div align="right">
{!! Form::submit(__('Convert Lead'), ['class' => 'btn btn-primary']) !!}
</div>
</div>
</div>
</div>
I am not sure which part of these are wrong, I think it is the form? When I click the Convert Lead button (to submit) nothing happens. Can anyone help? Thanks in advance.
try to place the form above the table tag
like this
<div>{!!Form::open(array('route' => array('leads.convertLeads', $lead->id)))!!}
<table width="100%">
<tr>
<th></th>
</tr>
<tr>
<td><li>Convert to Contact</li></td>

Route not going where it's supposed to

I'm getting this error. This error comes in when I hit the delete button
MethodNotAllowedHttpException in RouteCollection.php line 251:
the problem is as far as I know my routes is correct.
My cart.blade.php
#foreach($cartItems as $cartItem)
<tr>
<td>
<img src="{!! asset("product_images/$cartItem->img") !!}" alt="..." class="img-responsive">
</td>
<td>{!! $cartItem->name !!}</td>
<td>{!! $cartItem->qty !!}</td>
<td>R {!! $cartItem->qty * $cartItem->price !!}</td>
<td>
{!! Form::open(array('method' => 'Delete', 'route' => array('deleting', $cartItem->rowId))) !!}
<button class="btn btn-warning">Delete 2</button>
{!! Form::close() !!}
</td>
</tr>
#endforeach
My routes
Route::put('/product/deleting/{id}', [
'uses' => 'OpenController#deleting',
'as' => 'deleting'
]);
my controller
public function deleting($id)
{
echo "string";
}
You are using method DELETE on your form:
Form::open(array('method' => 'Delete',
but defined the method PUT in your route:
Route::put('/product/deleting/{id}', [
Try to change the route to
Route::delete('/product/deleting/{id}', [
Try using 'delete' instead of 'put' in your routes file.

storing data with name of author - laravel 5.2

I have hasMany relation to my model user and reports.
I want to set author name for the reports. (Like a blog-post author)
my model User:
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
model Report
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
and my controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
I'm able to set in in phpmyadmin, but how can i set it with my controller?
edit: my view:
{!! Form::open(['url' => '/dash/reports', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Servizio', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('title', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('date', 'Data lavorativa', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-2">
{!! Form::selectRange('day', 1, 31, null, ['class' => 'form-control']) !!}
{!! $errors->first('day', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::selectMonth('month', null, ['class' => 'form-control']) !!}
{!! $errors->first('month', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::select('year', array('2016' => '2016', '2015' => '2015'), null, ['class' => 'form-control']) !!}
{!! $errors->first('year', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : ''}}">
{!! Form::label('category_id', 'Cliente', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
Very easy. Replace Report::create... with this.
$user = Auth::user();
$report = new Report($request->all());
$report->author()->associate($user);
$report->save();
Make sure you use Auth; up at the top.
This uses the Auth object to get the current user,
Builds a new Report using the $request data without saving,
Tells the report we're associating $user as the author for the model,
Saves the report with the authorship information.
solution:
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

Update data with Laravel Collective forms

I have an edit form with Laravel Collective but when clicking the button, the data do not update. Below are my codes.
Form:
{!! Form::model($post, ['route' => ['/post/update/', $post->id]]) !!}
{{ method_field('PATCH') }}
<div class="form-group">
<div class="row">
<div class="col-lg-6">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="col-lg-6">
{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
</div>
</div>
</div>
<div class="form-group">
{!! Form::label('content', 'Content') !!}
{!! Form::textarea('content', null, ['class' => 'form-control', 'rows' => 10]) !!}
</div>
<hr/>
<div class="form-group">
{!! Form::submit('Update', ['class' => 'btn btn-success pull-right']) !!}
</div>
{!! Form::close() !!}
Controller:
public function edit($id)
{
return \View::make('admin/post/edit')->with([
'post' => \DB::table('posts')->find($id),
'categories' => \App\Category::lists('category', 'id')
]);
}
public function update(Request $request, Post $post)
{
$post->update($request->all());
return \Redirect::to('/admin/posts');
}
Routes:
Route::get('/admin/post/edit/{id}', 'Admin\PostController#edit');
Route::patch('/post/update/', [
'as' => '/post/update/',
'uses' => 'Admin\PostController#update'
]);
It's a bit different from the Laracast, and it's confusing me. Framework is new to me and the lack of code to do something is confusing.
I solved it. Mass Assignment. explains what to do if using update or create
So, the update method is:
public function update(Request $request, Post $post)
{
$post->title = $request->title;
$post->category_id = $request->category_id;
$post->content = $request->content;
$post->save();
return \Redirect::to('/admin/posts');
}

Resources