Laravel 5.8: Two round passing data between controller and blade - redirect

I am getting undefined variable when passing data from controller to blade the second time.
With Laravel 5.8, I have two actions/methods in a MyController. I have to pass data from controller to view. The first action works fine (MyController#action1 -> Blade1) but the second fails (MyController#action2 -> Blade2).
MyController:
public function action1()
{
...
$varialbe1 = ... // everything set correctly here and got it in blade1
return view('blade1', compact('variable1'));
}
public function action2(Request $request)
{
...
$association = $request->input('association');
return view('blade2', compact('association'));
}
Blade 1
<form method="POST" action="{{ route('route2') }}">
#csrf
<div class="form-group row">
<label for="association" class="col-md-4 col-form-label text-md-right">{{ __('Association') }}</label>
<div class="col-md-6">
<select required="required" id="association" class="form-control" name="association">
<option></option>
#foreach ($variable1 as $key => $val)
<option value="{{ $key }}">{{ $val->id }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>
Route
Route::post('/route2', 'MyController#action2')->name('route2');
Blade 2 (Undefined variable: association)
{{ $association }}
I have tried different ways to get data in MyController and different to pass data to Blade2 (the way that also works fine with the action1), including:
$association = Input::get('association');
return redirect()->to('/route2')->with('association', $association); // where route2 load the view

My route file seems good (MyController in the previous post = LoginController). Here is my route/web.php:
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/route2', 'Auth\LoginController#action2')->name('route2');

Got resolved from another forum.
Should add the action method to the list of exception methods in the middleware as follow:
$this->middleware('guest')->except(['logout', 'action']);
As controller has the below middleware in the constructor:
$this->middleware('guest')->except('logout');
If the User is already logged in, which is the case, they will be redirected to the /home and the controller method will never be reached.

Related

storing form and rout

I have problem on storing form . All my efforts will be damaged if I could not solve it.
The GET method is not supported for this route. Supported methods: POST.
what happen now :
1.When I press on register which is linked to this rout :
Route::POST('/jobs/apply/{id}/', [JobseekerController::class,'applyforjob'])->name('aplpy1');
there will be two scenarios:
if the user has cv it will register the user directly.(works)
if the user has not cv it will direct the user to create cv view .(works)
This is a part of create cv view :
<form method="POST" action="{{route('storing')}}" enctype=multipart/form-data>
#csrf
<input type="hidden" name=job_id value= {{$s}}>
#if (count($errors) > 0)
<div class="alert alert-danger alert-dismissible fade show">
<strong>Opps!</strong> Something went wrong, please check below errors.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="card-body">
<div class="container">
<!------ Include the above in your HEAD tag ---------->
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="accordion" class="checkout">
<div class="panel checkout-step">
<div> <span class="checkout-step-number">1</span>
<h4 class="checkout-step-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" > Personal Information</a></h4>
</div>
<div id="collapseOne" class="collapse in">
<div class="checkout-step-body">
<div class="row mt-3 pr-3">
<div class="col-6 ">
<strong>Full Name:</strong>
{!! Form::text('FName', null, array('placeholder' => 'Full Name','class' =>
'form-control pb-4')) !!}
</div>
<div class="col-6">
<div class="row mt-3 mr-2">
<strong>Nationality:</strong>
<select name="Nationality" class="custom-select">
#foreach(\App\Models\Nationality::all() as $nation)
<option value="{{$nation->name}}">{{$nation->name}}</option>
#endforeach
</select>
</div>
<div class="form-group ">
<button type="submit" name="submit" class="btn btn-primary ">{{ __('APPLAY') }}</button
</div>
<input type="hidden" name=job_id value= {{$s}}>
</form>
2.Now Here is the problem:
If I fill all the fields on the form correctly and click apply it works , but if there is missing field or anything not filled as it should be and then click apply , although there is validation on controller it does not work it gives this error:
The GET method is not supported for this route. Supported methods: POST.
Although I am using Post this my rout that I use to store the form
Route::POST('/jobsapply', [JobseekerController::class,'store'])->name('storing');
This my controller for storing:
public function store(Request $request )
{
$this->validate($request, [
'FName' => 'required|alpha|regex:/^([^"!\*\\]*)$/',
'Nationality' => 'required',
]);
$input = $request->all();
$input = $request->except(['_token']);
$cv = new cv();
if ($this->cvsave($cv, $request )) {
$data = Job::all();
$cv = auth()->user()->cv;
return view ('show',compact('cv' ,'data'))->with('success', 'CV created successfully.');
}
$data = Job::all();
return view('show')->with('Failed!', 'error');
}
public function cvsave(cv $cv, Request $request)
{
$cv->FName = $request->FName;
$cv->Nationality = $request->Nationality;
if ($cv->save()) {
$application = new JobApplication;
$id=$request->job_id;
$jobs = Job::find($id)->get();
$application->job_id =$request->job_id;
$user = User::find(auth()->user()->id);
$application->user_id = auth()->user()->id;
$cv = auth()->user()->cv;
$i= $cv->id;
$application->cv_id = $i;
$application->save();
\Session::flash('success', 'Thank you for applying! Wait for the company to respond.!');
return true;
}
return false;
}
I could not know the reason, I have read lots of stuff but still the same error

Passing Data from a Controller to a View (not displaying it) then passing back to different Controller in Codeigniter

I am trying to a create a View which provides a summary table of various site members profiles - then each summary has a button, that once clicked, takes the user to that member's full profile. I can get the summary page to work properly, but I cant get the second part -where the button takes the user to the members full profile to work.
Here is my controller:
public function network_barre()
{
$this->load->model("Profiles_model");
$style ='barre';
$profilesubdata["fetch_data"] = $this->Profiles_model->fetch_data($style);
$this->load->view('templates/header');
$this->load->view('pages/page-network_barre', $profilesubdata);
$this->load->view('templates/footer');
Here is my Model "Profiles Model"
function fetch_data($style)
{
$this->db->select("username, email, style, about");
$this->db->from("profiles");
$this->db->where('style', $style);
$query = $this->db->get();
return $query;
}
Here is the view
<div class="container">
<div class="row d-flex justify-content-center card-top">
<?php
if($fetch_data->num_rows()>0)
{
foreach ($fetch_data->result() as $row)
{
?>
<div class="col-lg-4 col-md-6">
<div class="card card-warning wow zoomInUp mb-4 animation-delay-5">
<div class="withripple zoom-img">
<img src="<?=base_url();?>assets/img/demo/avatar4.jpg" class="img-fluid">
</div>
<div class="card-body">
<span class="badge badge-warning pull-right"><?php echo $row->style; ?></span>
<h3 class="color-warning"><?php echo $row->username; ?></h3>
<p><?php $string=character_limiter($row->about, 255, '&#8230(More in Profile)') ; echo $string?></p>
<div class="row">
<div class="col text-center">
<!-- BUTTON -->
<form method="POST" action="<?php echo base_url(); ?>public_area/gotopublicprofile/<?php echo $row->email; ?>">
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
<button type="submit" class="btn btn-raised btn-sm btn-warning" name="submit" value="submit"><i class="zmdi zmdi-account"></i>Profile</button>
</form>
</div>
</div>
</div>
</div>
</div>
<?php //this tag close out php tags above
}
}
?>
</div>
</div>
here is Controller gotopublicprofile
function gotopublicprofile()
{
$this->load->model("profiles_model");
$email = '$this->uri->segment(3)';
$profiledata["fetch_profiledata"] = $this->Profiles_model->fetch_profiledata($email);
$this->load->view('templates/header');
$this->load->view('pages/page-profilepublic', $profiledata);
$this->load->view('templates/footer');
}
And here is the fetch_profiledata function in the Model:
function fetch_profiledata($email)
{
$this->db->where('email', $email);
$query = $this->db->get("profiles");
return $query;
}
I always get these error messages:
Undefined property: Public_area::$Profiles_model
AND
Call to a member function fetch_profiledata() on null
I am sure I am just missing something simple, as lots of websites use this approach.
Thanks in advance!
So I figured it out..it was a combination of little things:
First
$email = '$this->uri->segment(3)';
became
$email = $this->uri->segment(3);
Thanks #kirb! and
function gotopublicprofile()
{
$this->load->model("profiles_model");
became
function gotopublicprofile()
{
$this->load->model("Profiles_model");
Thanks #Atal Prateek!

Symfony 4 Form posting to a route

I have a problem with a form that deletes a doctrine object when posting in Symfony 4.I searched the problem and i only found that i might have to define a service? I am a beginner in symfony so dont blame me please... I am using datatables and the form is in a modal. When i press the delete button in the modal it tries to post to the route but an error comes up:
Service "request" not found: did you mean "request_stack"? Anyway, the container inside "App\Controller\ItemManagement" is a smaller service locator that only knows about the "doctrine", "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.csrf.token_manager", "session" and "twig" services. Try using dependency injection instead.
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteit">Delete Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Are you sure you want to delete this item?
<form action="{{ path('delete_item')}}" method="POST" id="theform" >
<input type="hidden" value="" name="itemtodel" id="itemtodel"/>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" form="theform" class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
In Controller:
/**
* #Route("/delitem", name="delete_item", methods={"POST"});
*/
public function deletetheitem(Request $request)
{
if ($request->isMethod('POST')) {
$itemid = $this->get('request')->request->get('itemtodel');
... deleting item code...
}
}
return $this->redirectToRoute("item_management", [], 301);
}
The route item_management is in the same controller and works fine. Am i doing it with the wrong way? Please if you have something to suggest i will appreciate it, thanks!!!!
try replacing
$this->get('request')->request->get('itemtodel')
by
$request->request->get('itemtodel')
First of all, you do not need to define any services since everything should work out of the box in the Symfony 4 (if you have not customize a default config).
Second, do not create static html forms in the template. Use Symfony Forms instead (https://symfony.com/doc/current/forms.html).
Third, you do not need to use request object if there should not be extra checks for query that get the object to delete. If you have not switched off param converter option (see https://symfony.com/doc/current/best_practices/controllers.html#using-the-paramconverter) of default Symfony 4, delete action could be like that:
/**
* #Route("/delitem/{item}", name="delete_item", methods={"POST"});
*/
public function deleteItemAction(Item $item)
{
$doctrine = $this->getDoctrine();
$em = $doctrine->getManager();
$em->remove($item);
$em->flush();
//process your response
}

Laravel 5: Form fields not in model

I have a model with a field called map_zips and inside that field, I would like to store up to 5 zip codes, comma separated.
I would like to have five different form fields that before getting stored in the database model, I concatenate the values together and store them in the DB in the single column.
How can I create multiple form fields in a view, validate said form fields, perform what needs to be done on said form fields, store them? Beyond that, I think I will also need to split them up when loading up the edit/update page as well.
I guess the simplest way would be to create 5 different columns, one for each zip, but I'd like to learn how to do this to help extend my limited knowledge of Laravel.
In my ReportsController.php my current store method looks like this:
public function store(Request $request) {
$this->validate($request, $this->rules);
$user = Auth::user();
$report = $request->all();
$report['user_id'] = $user->id;
Report::create($report);
return redirect('/reports')->with('status', 'Report created');
}
I don't know if i undertand you question but you can try this:
if you want 5 input fields in your view you can try this, you will see error messages from you validation and a returned message to confirm that the value was stored propperly
#if (count($errors) > 0)
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
</div>
#endif
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
<form action="{{ route("route_to_store_function") }}" method="post">
<input type="text" name="zip1">
<input type="text" name="zip2">
<input type="text" name="zip3">
<input type="text" name="zip4">
<input type="text" name="zip5">
<button type="submit"></button>
</form>
then in your store function, concatenate the fields, save the report and return with a message to the previous page:
public function store(Request $request) {
$this->validate($request, [
'zip1' => 'required',// you can add more validations here
'zip2' => 'required',
'zip3' => 'required',
'zip4' => 'required',
'zip5' => 'required',
]);
$report = new Report();
$report->map_zips = $request->zip1.",".$request->zip2.",".$request->zip3.",".$request->zip4.",".$request->zip5;
$report->save();
return redirect()->back()->with('message', 'The report has been stored succesfully');
}
Then when you want to edit the report you can try this:
public function edit($id) {
$report = Report::find($id)
$zipCodes = explode(",", $report->map_zips);
return view('edit_report_view', compact("report", "zipCodes"));
}
And in you edit view:
<form action="{{ route("route_to_update") }}" method="post">
<input type="hidden" name="id" value="{{ $report->id }}">
<input type="text" name="zip1" value="{{ $zipCodes[0] }}">
<input type="text" name="zip2" value="{{ $zipCodes[1] }}">
<input type="text" name="zip3" value="{{ $zipCodes[2] }}">
<input type="text" name="zip4" value="{{ $zipCodes[3] }}">
<input type="text" name="zip5" value="{{ $zipCodes[4] }}">
<button type="submit"></button>
</form>

My form is not populating when there is some validation error in the input data. Laravel Collective

Hope yo are all doing great.
I am using Laravel 5.3 and a package LaravelCollective for form-model binding.
I have subjects array that I want to validate and then store in database if there is no error in the input data.
The following snippets show the partial view of form, other views, rules for validations and controller code.
UserProfile.blade.php
<!-- Panel that Adds the Subject - START -->
<div class="col-md-12">
<div class="panel panel-default" id="add_Subject_panel">
<div class="panel-heading">Add Subject(s):</div>
<div class="panel-body">
{!! Form::open( array('method'=>'post', 'url'=>route('user.store.subject', 1)) ) !!}
#include('user.partials.subjects', ['buttonText'=>'Add Subject(s)'])
{!! Form::close() !!}
</div>
</div>
</div>
<!-- Panel that Adds the Subject - END -->
subjects.blade.php
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="subject-list">
<div class="input-group subject-input">
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
<span class="input-group-btn">
<span class="btn btn-default">Primary subject</span>
</span>
</div>
</div>
<div class="text-right">
<br />
<button type="button" class="btn btn-success btn-sm btn-add-subject"><span class="glyphicon glyphicon-plus"></span> Add Subject</button>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4 text-right">
<button type="submit" class="btn btn-primary">
{{ $buttonText }} <i class="fa fa-btn fa-subject"></i>
</button>
</div>
</div>
#push('scripts')
{{-- <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> --}}
<script src="{{ asset('scripts/jquery-2.2.4.min.js') }}" type="text/javascript" charset="utf-8" async defer></script>
<script>
$(function()
{
$(document.body).on('click', '.btn-remove-subject', function(){
$(this).closest('.subject-input').remove();
});
$('.btn-add-subject').click(function()
{
var index = $('.subject-input').length + 1;
$('.subject-list').append(''+
'<div class="input-group subject-input" style="margin-top:20px; margin-bottom:20px;">'+
'<input type="text" name="name['+index+']" class="form-control" value="" placeholder="Subject" />'+
'<span class="input-group-btn">'+
'<button class="btn btn-danger btn-remove-subject" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
'</span>'+
'</div>'
);
});
});
</script>
#endpush
I want to validate all the subjects passed as an array to the controller using a custom created form request. the following is the code for that form request
SubjectRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SubjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// dd("Rules Area");
foreach($this->request->get('name') as $key => $val)
{
$rules['name.'.$key] = 'required|min:5|max:50';
}
// dd($rules);
return $rules;
}
public function messages()
{
// dd('Message Area. . .');
$messages = [];
foreach($this->request->get('name') as $key => $val)
{
$messages['name.'.$key.'.required'] = ' Subject Name '.$key.'" is required.';
$messages['name.'.$key.'.min'] = ' Subject Name '.$key.'" must be atleast :min characters long.';
$messages['name.'.$key.'.max'] = ' Subject Name '.$key.'" must be less than :max characters.';
}
// dd($messages);
return $messages;
}
}
the following is the code for controller method I am using to store inputted array data to database.
public function storeSubjects(SubjectRequest $request)
{
$data = $request->all();
// save logic
dd($data);
}
Problem:
My form is not populating when there is some validation error in the input data.
After getting validation errors, my input fields are blank.
Problem
In subject.blade.php, your code looks like
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
Your fields are not populating because you have left value attribute blank.
Solution:
Pass the old value to solve your problem.
<input type="text" name="name[]" class="form-control" value="{{old('name[]')}}" placeholder="Subject" />
Use Form Model Binding instead
https://laravelcollective.com/docs/5.3/html#form-model-binding
{{ Form::model($user, [....]) }}
{{ Form::text('firstname', null, [...]) }}
{{ Form::close() }}