Select option in Laravel, how to store in a database? [duplicate] - laravel

Hello i´m new in laravel. I dont know how to store the value of a select in a variable.
This is how i do it in php. But how in laravel?
Thank you for help :)
<?php
session_start();
//Database
$servername = "127.0.0.1";
$username = "root";
$password = "root";
//Connection to Database
$conn = new mysqli($servername, $username, $password);
//Connection Test
if(!$conn) {
echo "Not connected to Server"
}
if(!mysqli_select_db($conn, 'test')){
echo "No connection to Database";
}
//store data in variable
$vorname = $_POST['name'];
$name = $_POST['age'];
?>
<!--Form Select-->
<form action="test.php" method="post">
<select name="name">
<option value="Lisa"></option>
<option value="Laura"></option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
<?php
$query = "SELECT * FROM test WHERE name = $name AND age = $age";
$profile = $conn->query($query);
?>
I want a Form with a select and the selected option should be stored in a variable.
Then checked in the database. And then show the results.
i dont know how to do thisin laravel.
thanks :)

All right let's get started. I suggest you study laravel documentation so things get more clear to you.
First of all you need to create your routes in your web.php file.
Route::get('/test', 'testController#index')->name('test.index');
Route::post('/values', 'testController#getValues')->name('test.values');
The first one will return your view the second one is to insert the data. Hang in there i will explain everything in the next lines.
Now you need a controller to handle the data and of course a view to preview your dropdowns.
In order to make a controller you can simple use php artisan make:controller testController command.
This will create a controller named testController like we named it in our routes.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
}
This is how your controller will look on this step. Simply return your view template (which i named it test for example pursposes). Now you actually need to create this view that you are trying to return. So inside the views file you create a test.blade.php file and post your html code a bit modified.
<form action="{{ action('testController#getValues') }}" method="post" id="postData">
{{ csrf_field() }}
<select name="name">
<option value="Lisa">Lisa</option>
<option value="Laura">Laura</option>
</select>
<select name="age">
<option value="20">20</option>
<option value="21">21</option>
</select>
<button type="submit">Sent</button>
</form>
You will notice that the action of the form is pointing straight to a controller function which will create in the next step. It's used to insert the data in the Database.
The csrf_field creates a token. For now you will realize that it helps your session not to "timeout" but does a lot more than that. Read more about it here!!!
The way to access your form is simple that's why laravel's routing makes things so simple. Go like "localhost/my_project_folder/test" and you should be able to see your view.
All right moving forward. Now you need to send the data from view to controller so you store it in the db.
We need a new function in the controller named getValues like we named it in the web.php file in the beginning. Now your controller should look like that:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class testController extends Controller
{
public function index()
{
return view('test');
}
public function getValues(Request $request){
$name=$request->get('name');
$age=$request->get('age');
$insertData=DB::table('data')->insert(
['name' => $name, 'age' => $age]
);
}
}
Request method is really useful in laravel so investigate some more about this method here!!!
Now the final part. Connect your database. All the connections happen in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testingdata
DB_USERNAME=root
DB_PASSWORD=root
This is my private database in my localhost so you can modify it using your credentials. After doing this step you are good to go.
If you have used different database or made a lot of changes etc etc and feel like you are using old settings run php artisan config:cache command to configure your cache with the latest changes.
This is the simplest walk through for insert data from the form to the database. You can optimize it and expand it a lot so my suggestion to you is to start reading laravel documentation, if possible get access to laracast and if you have time participate in the laracasts forum.

Related

retrieve database values in register page in laravel

I have registration auth in laravel project and i need some existing datas should show up on the registration form , please guide me up..
http://165.232.187.63/register
This is my register page and i need to fetch existing database values in the registration form. for example
<select>
#foreach($users as $items)
<option>{{ $items->id }}</option>
#endforeach
</select>
How to customize this...
I have tried adding in web.php file
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
And in my UserController.php
public function index()
{
$users = User::all();
return view('auth.register')
->with('users', $users);
}
But can't use both post and get for register auth
You need to use separate endpoints for this task
one to load the view
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
and the other to do the actual registration
Route::post('/register','App\Http\Controllers\Auth\UserController#register');
of course in the UserController, you will have a register method that handles the actual registration process

Laravel missing parameters to update form in controller

So I have a little project, in it, there's the possibility to upload banners images to be shown on the main page. All the stuff related to the DB are already created and the option to create a banner is working, it creates the banner and then stores the image on the DB for use later. Now I'm trying to work on an edit function so I can change the description under the bannners. I have an Edit route in my controller which returns a view where I edit said banner then it calls the update function on the controller. But no matter what I put here, I'm always getting the Missing Required Parameters error once I try to Save the edit and open my controller through the Update function. Here's the code as it is now:
The route definition:
Route::resource('banner', 'BannerController');
The edit function on my controller:
public function edit($id)
{
return view('admin/edit-banners',['id'=>$id]);
}
The update function has not been implemented because I always start with a dd() function to check if everything is working fine:
public function update(Request $request, $id)
{
dd($request);
}
And here's the form line in my edit view that is trying to call the update route:
<form class="card-box" action="{{ route('banner.update',[$banner]) }}">
I also added this at the beginning of the view to store the data from the DB into a variable:
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
The $banner variable contains all the information on the banner being edited, and I can get the new description at the controller with the $request variable, so I honestly don't know what should I put here as parameters, any ideas?
The $banner variable is not a Model instance, it is a Collection.
Adjust your controller to pass this to the view instead of dong the query in the view:
public function edit($id)
{
$banner = Banner::findOrFail($id);
return view('admin.edit-banners', ['banner' => $banner]);
}
You could also use Route Model Binding here instead of doing the query yourself.
Remove that #php block from your view.
The form should be adjusted to use method POST and spoof the method PUT or PATCH (as the update route is a PUT or PATCH route) and you should adjust the call to route:
<form class="card-box" action="{{ route('banner.update', ['banner' => $banner]) }}" method="POST">
#method('PUT')
If you include $id in your function declaration then when you call the route helper it expects you to give it an id parameter. Try with
<form class="card-box" action="{{ route('banner.update',['id' => $id]) }}">
You should be able to retrieve the form data just fine form the $request variable. More info here.
The code below should be the error source. $banner variable then is an array but the update function accept object or id.
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
You should try to replay this code by this one...
#php
use\App\Banner;
$banner = Banner::find($id);
//you should put a dd here to view the contain of $banner if you like
#endphp
Hop it help...

Laravel insert into mysql db from a controller function

I am trying to submit records into a mysql table with many fields by using a Laravel .blade.php view ( php form)
I made some trials but I get
FatalErrorException in loginController.php line 54: Class 'App\Http\Controllers\Input' not found.
Mysql
create table users(id int primary key auto_increment,username varchar(20),password varchar(20),createDate timestamp );
My controller function
public function formSubmit()
{
if (Input::post())
{
$username = Input::get('username');
$password = Input::get('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return View::make('view2')->with(array('username' =>$username, 'password' => $password));
}
}
view1.blade.php form
<form action="{{url('/view2') }}" method="POST">
{{ csrf_field() }}
<input type ="hidden" name="">
User name: <input type ="text" name="username"> <br/>
Password <input type="password" name="password"> <br/>
<input type="submit" name="formSubmit" value="formSubmit">
</form>
Route
Route::get('/view1', 'loginController#formSubmit');
Add use Input; to the top of your class right after namespace clause.
Or use full namespace:
$username = \Input::get('username');
$password = \Input::get('password');
Or you just could use only() method to get an array from request:
DB::table('users')->insert(request()->only('username', password));
Also, never save raw passwords. Use bcrypt() to encrypt passwords.
Since you're using Laravel 5, use the Request Facade and acces input this way:
Request::input()
instead of using Input();
https://laravel.com/docs/5.0/requests
And, just in case, include it at the top of the Controller with
use Illuminate\Support\Facades\Request;
Referring to Amarnasan answer I used request and include use Illuminate\Http\Request; at the top of my controller.
So I changed my controller method to
public function formSubmit(Request $req)
{
$username =$req->input('username');
$password =$req->input('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return view ('view2')->with(array('username' =>$username, 'password' => $password));
}
}
and I changed my routes according to Shubham pokhriyal commit to:
Route::post('/view2', 'loginController#formSubmit');
Route::get('view1',function()
{
return view('view1');
}
);
and it works fine.

Store method not working using resource route

I am having trouble figuring out why my data is not being posted and stored in my database. I have used the resource routes for another form and it works fine, but here for some reason it won't work. Clicking submit just seems to refresh the page, no errors to work from!
So I have a form which gets the workout routines from a database, and on submission I want this to create a new Workout "session" in my database table (called "Workouts"). The form is this:
{{ Form::open(array('url' => '/')) }}
<div class="form-group">
{{ Form::text('workout_name', Input::old('workout_name'), array('class' => 'form-control', 'placeholder' => 'Session Name')) }}
</div>
<div class="form-group">
{{ Form::select('routines', $routine_names, null, array('class' => 'form-control')) }}
</div>
{{ Form::submit('Select Routine', array('class' => 'btn btn-success pull-right')) }}
{{ Form::close() }}
In my HomeController I have this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Routine;
use App\Workout;
class HomeController extends Controller
{
public function index()
{
$routines = Routine::all();
$routine_names = Routine::lists('routine_name');
return view('workout')->with(array('routines'=>$routines, 'routine_names'=>$routine_names));
}
public function store()
{
$workout = new Workout;
$workout->workout_name = Input::get('workout_name');
$workout->save();
}
}
I have a model created for the Workout, and the route for this page is the following:
Route::resource('/', 'HomeController');
I can't figure out where I'm going wrong. The index method in my controller is working, as it is returning the correct view with the data I need. The form also looks OK I think, as I'm posting to the same page, but submitting doesn't seem to carry out the code I have in the store method of the HomeController.
Any help would be appreciated!
Thanks :)
Change your route declaration from:
Route::resource('/', 'HomeController');
To something like this:
Route::resource('/workout', 'WorkoutController');
If you are using the resources controller creator command of php artisan then all the specific routes are created for you. To see all listed routes you can type , php artisan routes. This will show you RESTFUL routes even for your POST method .
And also even you did not created the resources controller and did made the routes with manual way then you can create ,
Route::POST('/workout' , SomeController#post);
I am trying to say , you have to use the different POST method for the form submission .
Hope this will solve your problem . Thanks.

Building drop-down-list in Laravel (without models)

I am trying to make a drop down list in Laravel with the select options being values from my database and I have some issues. In other tutorials in this site, doing drop down list inquires building the models for your database. I have not created model classes and I do not intend to.
Routes.php
Route::get("/user/charname", array(
'as' => 'profile-character',
'uses' => 'ProfileController#dropDownList'
));
ProfileController.php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->pluck('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
In the profile.blade.php (view)
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
</li>
</form>
</div>
By doing this it says that $list from my view is undefined. Where do I define $list in the view and how will I carry $list from my Controller to the View because this line doesn't seem to do it's job
return View::make('layout.profile')->with('character_options',$list);
You need to use $character_options not $list in the View.
You actually specify that the variable should be 'character_options' in your View::make() call, so you need to refer to it as $character_options.
Additionally, ->lists('char_name') is better than using ->pluck('char_name') as it'll give you the full list. Pluck just returns the first item it finds.
Additionally to that, using ->lists('char_name', 'id') gets you the list keyed by the id column, which would be useful if you were to use this list to determine IDs for a foreign key field. But no biggie if not.
I have partially solved the issues by doing this in my view:
{{ Form::select('list', DB::table('characters')->where('char_id', '128')->lists('char_name') ,Input::old('list')) }}
Personally I do not see it as a viable solution, but a temporary one
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
Error: undefined variable character_options
{{ Form::select('character_options', $list ,Input::old('character_options')) }}
Error: undefined variable list
Maybe I do not understand how i send the variable from the Controller to the View.
You need to use lists as mentioned by #alexrussel. Do note that View::make('layout.profile')->with('character_options',$list);, here you are passing the variable $character_options with the value contained in the $list and $list will no longer be available to the view.
ProfileController.php
<?php
class ProfileController extends BaseController
{
public function dropDownList()
{
$list = DB::table('characters')->where('char_id', '128')->lists('char_name');
return View::make('layout.profile')->with('character_options',$list);
}
}
profile.blade.php
<div class="selected_char">
<form action="{{ URL::route('profile-character') }}" method="post">
<li>
{{ Form::select('character_options', $character_options ,Input::old('character_options')) }}
</li>
</form>

Resources