Laravel Eloquent Model - can't access database - php

I'm trying to write a simple site that can write and read of a simple mysql database, using Laravel, but I've run into a full stop as Laravel doesn't seem to be recognising my model. Either that or I am doing something wrong.
My model:
class Submission extends Eloquent
{
public static $timestamps = true;
protected $fillable = array('location', 'twitter', 'instagram', 'website');
}
My form:
#extends('layout')
#section('content')
{{ Input::old('twitter') }} <br />
{{ Input::old('instagram') }} <br />
{{ Input::old('website') }} <br />
{{ Form::open(array('url' => '/submission', 'files' => true)) }}
<div class="form-group">
{{ Form::label('twitter', 'Twitter') }}
{{ Form::text('twitter', '', array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('instagram', 'Instagram') }}
{{ Form::text('instagram', '', array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('website', 'Website') }}
{{ Form::text('website', '', array('class' => 'form-control')) }}
</div>
{{ Form::button('Submit image', array('class' => 'btn btn-success', 'type' => 'submit')) }}
<input type="hidden" name="post" value="yes">
{{ Form::close() }}
#stop
My controller:
public function postView()
{
$submission = new Submission;
$submission->twitter = Input::get('twitter');
$submission->instagram = Input::get('instagram');
$submission->website = Input::get('website');
$submission->save();
return Redirect::to('submission')->withInput();
}
My database looks like: id location twitter instagram website created_at updated_at
I know that my database config is correct as I can retrieve information using DB::table('submissions')->get(); so from what I can tell it's Laravel that's not recognising my model?
EDIT:
Turns out that changing public static $timestamps = true; to public $timestamps = true; fixed it.

Does this works :
DB::table('submissions')->get();
as it should return everything in the table. If it works then Eloquent can't find your table you can try to put that in your model:
protected $table = 'submissions';
It will define explicitly the table name in the model, even if it seems correct in your case
Otherwise you need to tell what exactly laravel answers when you made a request.
Do you have an error message in your browser ?
Do you have an error message in your log file (check the app/storage/logs folder)
Is your database configuration ok ? (app/config/database.php)
Did you create the table using a laravel migration ?
Hope it helps

Related

delete function Laravel 5.2

I've been learning laravel 5.2 recently, and i've made a delete function which should delete records from my database but instead of deleteing the records it's adding a blank row into my database
This is the Route im using:
Route::resource('producten', 'ProductenController', ['only' => ['index', 'store', 'destroy', 'edit', 'update', 'create']]);
This is the controller function i use for it
public function destroy(request $request , product $product)
{
$product->delete();
return redirect(Route('producten.index'));
}
This is the form i've made for it.
{{ Form::Open(['Route' => 'producten.destroy', $product], ['method' => 'delete']) }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
when i viewed the source-code it said it was using a POST method instead of a delete method, and also when i add($product) i got a blank page, also i found out that when i hit the submit button it goes to the store method i've made and i dont know why,
if u need more information just let me know and i'll add it in the question
route and method should be in the same array, not in two differents arrays.
{{ Form::Open(['method' => 'DELETE', 'route' => ['producten.destroy', $product]]) }}
{{ method_field('DELETE') }}
{{ Form::Submit('delete')}}
{{ Form::close() }}
I think you have something wrong with form. Can you try with this:
<form action="{{ route('producten.destroy', ['product' => $product->id]) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Remove</button>
</form>

Laravel form validation only works when hitting back button

I'm using Laravel 4.2. My issue happens after submitting the form with data that will fail during form validation (short pass, invalid email, etc).
My form is at /register. When I submit the form with invalid data, the page goes blank (white) and no data is entered into the database. The validation errors only show up after I hit the back button in the browser.
If I enter valid data, the form submits and adds data to the database correctly, and redirects the user to /account.
Any help would be greatly appreciated. I feel like it's something small that I'm overlooking, and it's kicking my ass.
Here's my code...
User.php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends BaseModel implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/** Protect from mass-assignment **/
protected $fillable = array('username', 'email', 'password', 'password_confirmation');
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
public static $rules = array(
'username'=>'required|unique:users,username|alpha_dash|min:4',
'password'=>'required|between:8,32|confirmed',
'password_confirmation'=>'required|between:8,32',
'email'=>'required|email|unique:users,email'
);
}
UsersController.php
class UsersController extends BaseController {
public function getNew() {
return View::make('users.new')
->with('title', 'Create An Account');
}
public function postCreate() {
$validation = User::Validate(Input::all());
if ($validation->passes()) {
User::create(array(
'username'=>Input::get('username'),
'password'=>Hash::make(Input::get('password')),
'email'=>Input::get('email')
));
return Redirect::to('account')->with('message', 'Welcome! Your account has been created.');
} else {
Redirect::to('register')->withErrors($validation)->withInput();
}
}
}
Routes.php
Route::get('register', array('as'=>'register', 'uses'=>'UsersController#getNew'));
Route::post('register', array('before'=>'csrf', 'uses'=>'UsersController#postCreate'));
new.blade.php
#if($errors->has())
<p>The following errors have occured:</p>
<ul id="form-errors">
{{ $errors->first('username', '<li>:message</li>') }}
{{ $errors->first('password', '<li>:message</li>') }}
{{ $errors->first('password_confirmation', '<li>:message</li>') }}
{{ $errors->first('email', '<li>:message</li>') }}
</ul>
#endif
{{ Form::open(array('action'=>'register')) }}
<p>
{{ Form::label('username', 'Username') }}<br />
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('email', 'Email Address') }}<br />
{{ Form::text('email', Input::old('email')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}<br />
{{ Form::password('password') }}
</p>
<p>
{{ Form::label('password_confirmation', 'Confirm Password') }}<br />
{{ Form::password('password_confirmation') }}
</p>
<p>
{{ Form::submit('Register') }}
</p>
{{ Form::close() }}
basemodel.php
class BaseModel extends Eloquent {
public static function validate($data) {
return Validator::make($data, static::$rules);
}
}
In your UsersController::postCreate() function you're not returning the Redirect::to() in your else{} and so the response isn't being sent back to the user. The controller is just executing without returning anything and so you're left with a blank page.
Redirect::to('register')->withErrors($validation)->withInput();
needs to become
return Redirect::to('register')->withErrors($validation)->withInput();

Symfony2 Customize the Form from the Simple Registration Tutorial

I've followed the guide and gotten the registration working just fine.
The only issue I have with this is the Form has a title:
User
I do not want this title. I want to customize this. How do I change this title.
As for code everything is as in the guide except my controller which is:
/**
* #Route("/SignUp", name="wx_exchange_signup")
* #Template("WXExchangeBundle:User:signup.html.twig")
* #Method({"GET"})
* User sign up - Open to public
* Creates new users based on information they provide
*/
public function signupAction(Request $request)
{
if ($this->get('security.context')->isGranted('IS_AUTHENTICATED_REMEMBERED'))
{
// redirect authenticated users to homepage
return $this->redirect($this->generateUrl('wx_exchange_default_index'));
}
$registration = new Registration();
$form = $this->createForm(new RegistrationType(), $registration, array(
'action' => $this->generateUrl('wx_exchange_signup_create'),
));
return array('form' => $form->createView());
}
The answer I finally found is to only display the form elements that you want:
<form action="/app_dev.php/SignUp/create" method="post" name="registration">
<div id="registration">
<div>
<div id="registration_user">
<div>
{{ form_label(form.user.email) }}
{{ form_widget(form.user.email) }}
</div>
<div>
{{ form_label(form.user.username) }}
{{ form_widget(form.user.username) }}
</div>
<div>
{{ form_label(form.user.password.password) }}
{{ form_widget(form.user.password.password) }}
</div>
</div>
<div>
{{ form_label(form.terms) }}
{{ form_widget(form.terms) }}
</div>
<div>
<button name="registration[Sign Up]" id="registration_Sign Up" type="submit">Sign up</button>
</div>
{{ form_widget(form._token) }}
</div>
</form>
This is documented in the Symfony forms chapter.

Method validateConfirm does not exist (Laravel)

I am following Dayle Rees' Laravel tutorial, trying to build a simple registration page.
If I submit the registration form with validation errors, the page reloads and shows me the validation errors. However, when I key in correct values and submit, I get the following error -
BadMethodCallException
Method [validateConfirm] does not exist.
This is my register.blade.php -
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<h1>Registration form</h1>
{{ Form::open(array('url' => '/registration')) }}
{{-- Username field. ------------------------}}
{{ Form::label('username', 'Username') }}
{{ Form::text('username') }}
{{ $errors->first('username', '<span class="error">:message</span>') }}
<br/>
{{-- Email address field. -------------------}}
{{ Form::label('email', 'Email address') }}
{{ Form::email('email') }}
{{ $errors->first('email', '<span class="error">:message</span>') }}
<br/>
{{-- Password field. ------------------------}}
{{ Form::label('password', 'Password') }}
{{ Form::password('password') }}
{{ $errors->first('password', '<span class="error">:message</span>') }}
<br/>
{{-- Password confirmation field. -----------}}
{{ Form::label('password_confirmation', 'Password confirmation') }}
{{ Form::password('password_confirmation') }}
<br/>
{{-- Form submit button. --------------------}}
{{ Form::submit('Register') }}
{{ Form::close() }}
</body>
</html>
And this is my routes.php [NOTE : The issue goes away if I remove the rule for password]
Route::get('/', function()
{
return View::make('register');
});
Route::post('/registration', function()
{
// Fetch all request data.
$data = Input::all();
// Build the validation constraint set.
$rules = array(
'username' => 'required|min:3|max:32',
'email' => 'required|email',
'password' => 'required|confirm|min:3'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
// Normally we would do something with the data.
return 'Data was saved.';
}
return Redirect::to('/')->withErrors($validator);
});
Issue seems to be due to using confirm instead of confirmed. Resolved!
you can include ->back() or use
must be changed in your code , its required
return Redirect::to('/')
->back()
->withErrors($validator);

Laravel 4 getting information from database for drop-down form

I am trying to make a simple authentication application and I have the login/signup form in place and it is working correctly. However, I am having issues with populating the drop-down field for a zip-code from another table. I am not really sure how i should approach this. Most of the time i would just use straight mysql query but I am assuming there is an easier way.
Controller: (would love for the zip_code table to go here.)
public function getSignUp() {
$userdata = array(
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password'))
);
$user = new User($userdata);
$user->save();
return Redirect::to('dashboard');
}
Route
Route::post('signup', 'LoginController#getSignUp');
signup.blade.php
{{ Form::label('email', 'Email:') }}<br />
{{ Form::text('email') }}<br />
{{ Form::label('password', 'Password:') }}<br />
{{ Form::password('password') }}<br />
{{ Form::label('zip_code', 'Zip Code:') }}<br />
{{ Form::select('zip_code', array('zip_code' => '', 'city' => '')); }}<br />
{{ Form::submit() }}<br />
{{ Form::close() }}
This is how I would normally call database information before this
public function showHome()
{
$testimonials = DB::select('SELECT * FROM `testimonials` WHERE `id`=' . mt_rand(1, 2));
return View::make('home.index', array('pageTitle' => 'Home'))->with('testimonials', $testimonials);
}
but with me not returning a view and therefor no variables are going to be passed I am not sure how to achieve this
Any advice would be highly appreciated!
You can easily list out data from an Eloquent model for a select field using the lists() function.
Testimonial::lists('content', 'id');

Categories