laravel pass data from blade file to Controller - php

I am trying to take data that a user inputs into a form, created in blade, and transport that data to my controller. At that point I can use a function in my controller to write the data into MySQL.
Here is the code for the form which I have in my blade file.
<form action="{{ route("users") }}" method="post">
<input type ="form" id="firstname"> firstname </input> <br>
<input type ="form" id="lastname"> lastname </input> <br>
<input type="form" id="email"> email </input> <br>
<input type="form" id="userlevel"> userlevel </input> <br>
<input type="form" id="password"> password </input> <br>
<br> <br>
<button type="submit"> Submit
</button>
</form>
Here is the code in my controller which writes data into MySQL. The code works when I am using dummy data, instead of the $name and $lastname variables.
public function users()
{
$name = $_POST["firstname"];
$lastname = $_POST["lastname"];
DB :: table("newUsers") -> insertGetId
(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}
I am currently getting an error that says
Undefined index: firstname
Ideally what I want to happen is for whatever the user entered for firstname and lastname to be written into my MySQL table.

You need to add name attributes to your inputs and format them correctly they should look more like:
<input type="text" id="firstname" name="firstname"></input>
If you are placing 'firstname' between your openning and closing input tags for a placholder value use the placeholder attribute instead.
<input type="text" id="firstname" name="firstname" placeholder="first name"></input>
But do be warned the placeholder attribute doesnt work in older browsers
Also dont use $_POST laravel has built in ways of getting the values from your form.
Laravel 5
$request->input('firstname');
like this:
public function users(Request $request)
{
$name = $request->input('firstname'); // This is better than using $_POST
$lastname = $request->input('lastname');
DB :: table("newUsers") -> insertGetId
(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}
Notice, I have passed in Request $request like a variable in the method users. You will also need to add use Illuminate\Http\Request as Request; to the top of your class:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request as Request; //here
class MyController extends Controller
{
}
Laravel 4
Input::get('firstname');

Change your Form as follows:
<form action="{{ route("users") }}" method="post">
<input type ="form" name=firstname" id="firstname" placeholder="First name">
<input type ="form" name=lastname" id="lastname">
<input type="form" name="email" id="email">
<button type="submit"> Submit </button>
</form>
You've to provide the name attribute to your form fields.
And in the controller, you don't have to use $_POST anymore.
Just use:
public function users(Request $request)
{
$firstname = $request->input('firstname');
$lastname = $request->input('lastname');
DB :: table("newUsers") -> insertGetId(
array("firstname" => $name, "lastname" => $lastname, "email" => "test")
);
return view("pages.users");
}

You can access form data with $request->get('first_name'), for example.
To make it work, add name tags to your form inputs and catch data, for example, if you use store action:
function store(Request $request){
}
In this case you also can easily validate input data by using custom Reuqest classes:
https://laravel.com/docs/master/validation#form-request-validation

Related

Laravel: How to get ID from Papers Table to Store in Bookmarks Table

I can't get the PaperID to store into my Bookmarks DB
here is my controller for the bookmark store function
public function store(Request $request)
{
$request->validate([
'BookmarkName' => 'required',
]);
$paper = DB::table('papers')
->where('PaperID', '=', $request->paper_id)
->value('PaperID');
$bm = new Bookmarks();
$bm->BookmarkName=$request->BookmarkName;
$bm->paper_id = $paper;
$bm->save();
return redirect()->back()->with('success','Bookmark Added');
}
here is the form to call the function
<form class="bookmarkInput" action="{{ route('Bookmarks')}} " method="POST" >
#csrf
<div class="group">
<input class="inputInfo" type="text" name="BookmarkName" required>
<span class="highlight"></span>
<span class="bar"></span>
<label class="infoLabel">Bookmark Name</label>
</div>
<br>
<br>
<button class="redBtn" type="submit">Add</button>
</form>
here is the route for it
Route::post('/Bookmarked', [App\Http\Controllers\BookmarkController::class, 'store'])->name('Bookmarks');
I do not know why it isn't getting the ID calling papers DB seems good but it doesn't want to get the current ID of the paper I want to bookmark
You are not passing paper_id from form.
That's why your ->where('PaperID', '=', $request->paper_id)
don't have value of paper_id.
you can pass paper_id from form by using hidden input field.
<input type="hidden" name="paper_id" value = {{ $paper_id }}>
Remember to pass paper_id variable containg paper_id value to the blade having form.
Also add ->first() before ->value('PaperID').

Send Input values from one page to another

I'm working on Laravel project and I want to send my input values from the FORM from one page (the inscription page) to a pdf page (which I want the user to be able to download). I couldn't find a way to send them from that page to the other
input:all
using the $request in the controller
<div class="fieldgroup">
<input type="text" style="color:0B0C51" onclick="submitform2()" name="cin" id="cin"
placeholder="NĀ°CIN" maxlength="8" class="required"></i><br>
</div>
<div class="fieldgroup">
<input type="text" style="color:0B0C51" v-model="prenom" name="prenom" id="prenom"
placeholder="Prenom" class="required"><br>
</div>
<div class="fieldgroup">
<input type="text" style="color:0B0C51" v-model="nom" onclick="submitform2()" name="nom"
id="nom" placeholder="Nom" class="required"><br>
</div>
<div class="fieldgroup">
<input type="mail" style="color:0B0C51" name="email" id="email" placeholder="Email"
class="required" />
</div>
ViewController :
class ViewController extends Controller
{
public function generatePDF(Request $request){
$request=this.
$data="form";
$pdf= PDF::loadView('pdf',compact('data'));
return $pdf->download('Terms.pdf');
}
}
web.php:
Route::get('/pdf','ViewController#generatePDF');
inscriController:
public function store(Request $request)
{
$cin = $request->input('cin');
$data = array(['cin'=>$cin ]);
DB::table('form')->insert($data);
return redirect('/pdf')->withInput();
This returns an empty form page without the input values
It may be easier to load the pdf right in the store method of inscriController. As it is, you are redirecting and passing no data into the pdf generator / view. You set $request as the controller ($this), which has none of the form data, and then you pass a single word 'form' as your data-set into the PDF generator. I don't think this will work the way you wish - I assume the pdf view is looking for specific variables (not 'form'), and thus it is failing because those vars are missing. IE you'd want to pull those vars like $name = $request->get('name') and pass whatever pdf.blade.php view needs from your $request var.
If you don't want to do it all in the store function, perhaps pass it to a method in the same inscriController? This way you can easily push the actual request object into that method and pull the fields you need for the PDF view.
use $input = $request->all(); for getting the data and in same function instead of redirect u can just return view for your /pdf route.
like return view('yourpath.pdf', compact('input'));

Laravel form submission with url parameters

When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}

Getting value from html inputs in Laravel app to send to mysql database?

I just started learning Laravel and would like to make a dummy Account Manager. My first goal is to be able to add accounts to the mysql db via an html form/Eloquent model/controller/migration. Coming from JavaScript, I'm not really sure how to pass the data from the name or value attr to the correct method and on to the migration. Here's my code from the form:
<form method="POST" action="/addAccount">
{{ csrf_field() }}
<input class="inputs" type="text" name="fname" placeholder="First Name">
<input class="inputs" type="text" name="lname" placeholder="Last Name">
<input class="inputs" type="email" name="email" placeholder="Email">
<h3>Account Types and ID's:</h3>
<ul class="list">
<li>Confirmation: 1</li>
<li>Setup: 2</li>
<li>Activated: 3</li>
<li>Deactivated: 4</li>
</ul>
<input class="inputs" type="number" name="ati" placeholder="Enter Account Type ID">
<input class="inputs" type="checkbox" name="active"><p>Click to Activate!</p>
<button class="button">Submit</button>
</form>
web.php: Route::post('addAccount', 'AccountsController#store');
Code for AccountsController:
public function store(Request $request)
{
$accounts = new Account;
$accounts->first_name = $fname;
$accounts->last_name = $lname;
$accounts->email = $email;
$accounts->account_type_id = $ati;
$accounts->active = $active;
$accounts->save();
return redirect('/');
}
Currently getting an ErrorException of "Undefined variable: fname". Any hints would be greatly appreciated!
You just need to use
$request->fname
instead of
$fname
In your form, please add :
{{ csrf_field() }}
Laravel checks if a form has a token to protect the application from CSRF attack. See link for more details. CSRF Protection
Also, add a name attr in your input types like so:
<input class="inputs" type="text" name="fname" placeholder="First Name">
In your web.php :
Route::post('addAccount', 'controllerName#controllerFunction');
In your controller:
function controllerFunction(Request $request){
//$request contains all sent data.
$fname= $request->input('fname'); #you can use this way
$fname = $request->fname; #or this one
....
//code for storing in DB using Eloquent
$users= new Users;
$users->first_name = $fname;
....
$users->save();
}
Please check the document for using Laravel Eloquent

codeigniter setting up a password!

I try to set up a password in a codeigniter form...
Everything seems ok to my eyes but no matter which password I use the form is still submitted...
here is the code in the controler:
class MyBlog extends Controller{
function MyBlog(){
parent::Controller();
$this->load->helper(array('url','form','html')); //here we load some classes that we use
$this->load->scaffolding('entries'); //scaffolfing is a feature that lets you add or remove elements from the database
$this->load->scaffolding('comments');
$this->load->library('form_validation');//load validation class used to validate our forms...
}
function index(){
$data['title'] = "My Blog Title"; //the title of my blog
$data['query'] = $this->db->get('entries'); //here we make a small query to entries table
$this->load->view('myBlog_view', $data); ///load all data variables on myBlog_view.php
//this is also for the form validation
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_rules('author', 'Author', 'required');
$this->form_validation->set_rules('pass', 'Pass', 'callback_pass_check');
function pass_check($str) {
if ($str == 'baywatch'){
return TRUE;
}
else{
return FALSE;
}
}
if ($this->form_validation->run() == TRUE)
{
$this->myBlog_insert();
//$this->load->view('formSuccess_view');
}
}
function myBlog_insert(){
$insert = array( 'title' => $_POST['title'],
'body' => $_POST['body'],
'author' => $_POST['author']
);
$this->db->insert('entries',$insert);
redirect('myBlog/');
}
}
and this is my form:
<div class="theForm">
<?php echo $this->form_validation->error_string; ?>
<?php echo validation_errors(); ?>
<?php echo form_open('myBlog'); ?>
<label for="title">Title:</label>
<input type='text' name="title" size="40" id="title" />
<p>
<label for="body">Body:</label>
<textarea name="body" rows = "10" cols="60" id="body"></textarea>
</p>
<p>
<label for="author">Author:</label>
<input type="text" name="author" size="40" id="author"/>
</p>
<p>
<label for="pass">Password:</label>
<input type="password" name="pass" size="38" id="pass"/>
</p>
<p><input type="submit" value="Submit New Post"/></p>
</form>
</div>
</body>
</html>
any ideas?
thanks in advance
<label for="pass">Password:</label>
<input type="text" name="pass" size="38" id="author"/>
The input type is text no password, the id='pass'.
Ok, a couple of things first:
1) id's should be unique. ie your author field and your password field shouldn't have the same id.
2) password fileds should use the type "password" not "text".
I think the reason you're having problems is with your callback function pass_check(). Try changing your function to:
function pass_check($pass)
{
if($pass !== 'baywatch')
{
return FALSE;
}
By the way, scaffolding has now been deprecated. Can I suggest you look into using models and the active record class as a way of interacting with your db? Also, this really isn't a very secure way of handling passwords. Have a look at some of the CI authentication libraries and see if you can implement one of them.
Ok guys...I found what the problem was...function pass_check was declared inside index()...and for some reason it needs to be outside as a method of the class...Hope this will help others... I give some ups for all the suggestions...

Categories