This is my code for SubscriptionController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SubscribersController extends Controller
{
//
//This method is to process the form
public function postSubmit() {
//we check if it's really an AJAX request
if(Request::ajax()) {
$validation = Validator::make(Input::all(), array(
//email field should be required, should be in an email//format, and should be unique
'email' => 'required|email|unique:subscribers,email'
)
);
if($validation->fails()) {
return $validation->errors()->first();
} else {
$create = Subscribers::create(array(
'email' => Input::get('email')
));
if($create){
return Redirect::to('/')
->with('success','You have been successfully subscribe to us.');
}else{
echo 'We could not save your address to oursystem, please try again later';
}
}
} else {
return Redirect::to('subscribers');
}
}
}
This is my code for Eloquent
class CreateSubscribersTable extends Migration
{
public function up()
{
Schema::table('subscribers', function (Blueprint $table) {
$table->increments('id');
$table->string('email,100)->default('');
$table->timestamps();
});
}.....
In the Route/web :
Route::post('/subscribers', 'SubscribersController');
This is the code for welcome.blade.php
<form action="/subscribers" method="post">
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</div>
</form>
The code dont insert in database and dont show any error in the console. I put in the postsubmit function echos if error appears and nothing.
I already search one tutorial and dont find.
I´m a noob in Laravel.
Routes should be Route::post('/subscribers','SubscribersController#postSubmit');
and add csrf_field() to form.
<form action="/subscribers" method="post">
{{csrf_field()}}
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</div>
</form>`
In your routes file, your route need to send to an action, not just the controller.
Route::post('/subscribers', 'SubscribersController');
should be this
Route::post('/subscribers', 'SubscribersController#postSubmit');
And add the csrf field to your html form:
<form action="/subscribers" method="post">
{{ csrf_field() }}
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</form>
First of all, did you run :
php artisan migrate
Second, as Hollings stated above, your route :
Route::post('/subscribers', 'SubscribersController#postSubmit');
Third, top of your SubscribersController, add :
use Subscribers;
Aside of having CreateSubscribersTable extends Migration, you need to have another model class named Subscribers which extends Model. All class you might need to have :
SubscribersController extends Controller (you have it)
CreateSubscribersTable extends Migration (you have this too)
Subscribers extends Model/Eloquent (Do you have this?)
Sorry, that are all i can figure. Will try to check more to help.
Or if you really dying to figure out where the problem is, try to put echo something maybe "Test", within each of your if else.
1) Your migration content is wrong
public function up()
{
Schema::create('subscribers', function (Blueprint $table) { //** 'create', not 'table'
$table->increments('id');
$table->string('email,100)->default('');
$table->timestamps();
});
}
Delete your db contents and php artisan migrate
2) Your form is
<form action="/subscribers" method="post">
{{ csrf_field() }} //** add token
<input type="email" name="email" placeholder="Email Address" required>
<button type="submit" class="btn btn-danger">Subscribe</button> //** Button type : submit
</div>
</form>
Your route:
Route::post('/subscribers', 'SubscribersController#postSubmit');
Your controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Subscribers; //********* change this
class SubscribersController extends Controller
{
//This method is to process the form
public function postSubmit(Request $request) {
$validation = Validator::make($request->all(), [
//email field should be required, should be in an email format, and should be unique
'email' => 'required|email|unique:subscribers,email',
]);
if($validation->fails()) {
return $validation->errors()->first();
}
$create = Subscribers::create(array(
'email' => $request->email,
));
return Redirect::to('/')->with('success','You have been successfully subscribe to us.');
}
}
Add protected $table = 'subscribers'; to your Subscribers Model.
Why are you using if (Request::ajax()) ? You are not submitting form via AJAX.
Related
At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you
I have a project that is going to have 8 different forms all updating the same 'user' table in my database. I have the user authentication working and it makes a user in the table on my localhost mysql database. However when I start updating the table I keep getting errors such as email is not unique or http errors or ReflectionException in RouteDependencyResolverTrait.php line 57: Internal error: Failed to retrieve the default value.
I have tried everything, my create works but it makes a new row and doesn't update the existing row which the user is signed in on.
I'm only new to Laravel 5.4 and finished going through all the Laracasts, so I'm absolutely stumped at what to do.
Does anyone have any thoughts or know how to fix it or restructure it better? Please let me know if I have missed anything out. I have been trying to get this working for 2 days.
Basics.php
<?php
namespace App;
class Basics extends Model
{
public $table = "users";
protected $fillable = [
'family_name',
'given_names'
];
}
BasicsController.php
class BasicsController extends Controller
{
public function index()
{
$user = \Auth::user();
return view('/details/basics', compact('user'));
}
public function update(Request $request, $id)
{
$basics = Basics::find($id);
$basics->family_name = $request->input('family_name');
$basics->given_names = $request->input('given_names');
$basics->save();
return redirect("/details/basics");
}
}
basics.blade.php
#extends ('layouts/app')
#section ('content')
{{--Do #includes for all form components with the components file--}}
#include ('layouts/header')
<main class="main">
<form action="/details/basics" method="POST">
<input type="hidden" name="_method" value="PATCH">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<label>Family name</label>
<input type="text" name="family_name" placeholder="Family name" value="{{ old('family_name') }}" />
</fieldset>
<fieldset>
<label>Given names</label>
<input type="text" name="given_names" placeholder="Given names" value="{{ old('given_names') }}" />
</fieldset>
<button type="submit" value="Save" name="save" class="button button-primary button-wide">Save</button>
</form>
</main>
#endsection
web.php
Route::get('/', function () {
return view('welcome');
});
// Authentication Routes
Auth::routes();
Route::get('/logout', 'Auth\LogoutController#destroy');
Route::get('/home', 'DashboardController#index');
Route::get('/dashboard', function () {
$user = Auth::user();
return view('dashboard', compact('user'));
});
// Eligibility Assessments
Route::get('/assessment/student', 'AssessmentController#index');
Route::post('/assessment/results', 'AssessmentController#store');
// Details
Route::get('/details/basics', 'BasicsController#index');
Route::patch('/details/basics', 'BasicsController#update');
You need to add a rule in your post request which will exclude the email field when updating the model. This is why you're getting the email is not unique error. Although you're not posting the email field but still the save method is doing that. Try using post instead of patch. Just for debugging purposes in your Route.php
I'm newbie to Laravel and got stuck with login mechanism I'm using my custom login mechanism here (not using Laravel Authentication) and there I'm not able to login with authenticate credentials.
I want to login with credentials and after login the log should be maintain in login_master and redirected to home. but it is not maintaining plus if the credentials are wrong then it should redirect back to signin.blade.php but it's redirecting to home.
Here is the code
create_login_table.php (My Login Table Structure)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLoginTable extends Migration
{
public function up()
{
Schema::create ('login_master',function($table)
{
$table->increments('login_id',true);
$table->integer('user_id')->unsigned();
$table->date('login_date');
$table->date('login_time');
});
// to create foreign key :)
Schema::table('login_master', function($table) {
$table->foreign('user_id')->references('user_id')->on('registration_master');
});
}
public function down()
{
Schema::dropIfExists('login_master');
}
}
LoginController (Controller for working with table)
namespace App\Http\Controllers;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Validator;
class LoginController extends Controller
{
public function loginform()
{
return view('signin');
}
public function authenticate(Request $request)
{
$userdata= Input::all();
$rules= array(
'email' => 'required|email',
'password' => 'required| min:6',
);
$validator = Validator::make($userdata,$rules);
if($validator->fails())
{
redirect('/signin')->withInput(Input::except('password'))->withErrors($validator);
}
else
{
$userdata= array(
'email' => Input::get('email'),
'password' => Input::get('pwd')
);
if(Auth::validate($userdata))
{
if(Auth::attempt($userdata))
{
$email= $userdata['email'];
$password= $userdata['password'];
$live_date=Carbon::now();
$log_date=$live_date->toDateString();
$log_time=$live_date->toTimeString();
$user_id= DB::select('select user_id from registration_master where email= ? and password = ?',[$email, $password]);
$record= DB::insert('insert into login_master
(user_id, login_date, login_time) values(?, ?, ?)',[$user_id, $log_date, $log_time]);
echo $email;
echo $password;
return Redirect::intended('/');
}
}
else
{
Session::flash('error', 'Something went wrong');
return Redirect::to('signin');
}
}
}
public function logout()
{
Auth::logout();
return Redirect::to('signin');
}
}
signin.blade.php (view for login)
<html>
<head>
<title>App Name - #yield('title')</title>
#include('library')
</head>
<body>
#include('header')
<div class="form-content">
<div class="headingstyle form-title">
<h1 class="heading1">Log in!</h1>
</div>
<form method="post" action="/home">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="formgroup">
<input class="input" type="text" name="uemail"required>
<label class="label">Email</label>
</div>
<div class="formgroup">
<input class="input" type="password" name="pwd"required>
<label class="label">Password</label>
</div>
<div class="formgroup bottomstyle">
<div id="check-awesome" class="form-group checkbox">
<input type="checkbox" id="RememberMeUser" mame="RememberMeUser">
<label for="RememberMeUser">
<span></span>
<span class="check"></span>
<span class="box"></span>
Remember Me
</label>
</div><!--Login-->
<input type="submit" value="Login"><br>
<a data-dismiss="modal" class="button cancelbtn">Cancel</a><br>
<span class="links"> <a class="bottomlink" href="#">Forgot Password?</a></span><br>
<span class="links">New User
<!--<a class="bottomlink" href="#" data-dismiss="modal" data-toggle="modal" data-target="#id02">Sign Up?</a> -->
{{ Html::linkAction('SignUpController#signupform','Sign Up', array(), array('class' => 'bottomlink')) }}
</span>
</div>
</form>
</div>
<div>
#include('footer')
</div>
</body>
</html>
You will need to configure app/auth.php or dotenv to use your own custom model with the Auth Guard helper in Laravel. There you can set the model and table you want to use.
Else you could implement your own Auth helper/facade to save logged_in_user_id in session. Your custom authentication will basically confirm the passed user credentials and store the logged_in_user_id in session. Your logout method will likewise clear this id from session when called.
I have problem to save name and email from user1 in table user1s that I have made .
When I enter them in textareas using html form in Laravel with route::post and function store it is not working. When I enter text and hit the button Register it outputs the following error:
MethodNotAllowedHttpException in RouteCollection.php line
You will see that I use the HTML form and that I have tried to add <input ....> into my form.
Here are my files:
route.php
<?php
Route::get('/','PageController#home');
Route::post('/','User1Controller#store');
Route::get('about','PageController#about');
welcome.blade.php
I'm not sure about the action.
After putting user1 inf into table, it should be redirected to a "Thank you" page (I have a thankyou.blade.php ) , maybe that is the problem
<form method="POST" action="">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<ul class="list-group" >
<li >
NAme
<div class="form-group" title="email" >
<textarea name="name" class="form-control" >
</textarea>
</div>
</li >
<li>Email
<div class="form-group" >
<textarea name="email" class="form-control" >
</textarea>
</div>
</li>
<li >
<div class="form-group" >
<button class="btn btn-primary">Register</button>
</div>
</li>
</ul>
</form>
migration for user1
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('card_id')->unsigned();
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::drop('notes');
}
}
user1controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class User1Controller extends Controller
{
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return view('thankyou');
}
}
pagecontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class PageController extends Controller
{
public function home()
{
$user1s= User1::all();
return view('welcome',compact('user1s'));
}
public function about()
{
return view('pages.about');
}
}
Your form is basically a registration form. I would recommend using a more meaningful name for the end point. The post route can be something like,
Route::post('/register','User1Controller#store');
Now the form action can be,
action="/register"
I corrected the typo.Thanks!
I have also changed this
Route::post('/','User1Controller#store');
and action=" " .
It works ,the only thing right now that is not good is that I should redirect to a page "Thank you" not go to anther view on the exact same page.
Because It makes a mess in the database when I reload the home page.
I'll try that and tell if it works.
Thank you people for the help! :)
Things solved,this works. I will add the code that i have added so the other can find it!
Firs of all : I haven't figured why ,but action="dir1/dir3" for me didn't work!
Here are the added things!
routes.php
Route::get('thankyou','PageController#thankyou');
***PageController.php***
public function thankyou()
{
return view('thankyou');
}
*****User1Controller.php*****
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect('/thankyou');
}
I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.