check if value already exists in db - laravel

I have an insert form and a dropdownbox which displays all cars names and when selected one it saves the id in column "car_id" which is unique. What I want is to check if this id already exists and if yes to display a validation message:
create controller
public function create() {
$cars = DB::table('cars')->orderBy('Description', 'asc')->distinct()->lists('Description', 'id');
return View::make('pages.insur_docs_create', array(
'cars' => $cars
));
}
insur_docs_blade.php
<div class="form-group">
{{ Form::label('car', 'Car', array('class'=>'control-label col-lg-4')) }}
<div class="col-lg-8">
{{ Form::select('car', $cars, Input::old('class'), array(
'data-validation' => 'required',
'data-validation-error-msg' => 'You did not enter a valid car',
'class' => 'form-control'))
}}
</div>
</div>

You can use Laravel's Validator class for this. These are a few snippits of how it works. This methods works by using your data model. Instead of writing everything out I added a few links that provide you all the information to complete your validation.
$data = Input::all();
$rules = array(
'car_id' => 'unique'
);
$validator = Validator::make($data, $rules);
if ($validator->passes()) {
return 'Data was saved.';
}
http://laravelbook.com/laravel-input-validation
http://laravel.com/docs/validation
http://daylerees.com/codebright/validation

You can use Laravel's "exists" method like this:
if (User::where('email', $email)->exists()) {
// that email already exists in the users table
}

Related

Image Upload => LogicException Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)

I'm following the following tutorial -> http://laraveldaily.com/upload-multiple-files-laravel-5-4.
When I go to post my advert, the add goes thorugh without the photographs. My error message is
Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)
I have enabled php_fileinfo and restared the server, but to know avail. Any other ideas on how to fix this?
public function store(Request $request){
$Advert = PropertyAdvert::create([
"address" => $request->address,
"county" => $request->county,
"town" => $request->town,
"type" => $request->type,
"rent" => $request->rent,
"date" => $request->date,
"bedrooms" => $request->bedrooms,
"bathrooms" => $request->bathrooms,
"furnished" => $request->furnished,
"description" => $request->description,
"user_id" => Auth::id(),
]);
foreach ($request->photo as $photo) {
$filename = $photo->store('photo');
PropertyAdvertPhoto::create([
'property_id' => $Advert->id,
'filename' => $filename
]);
}
$id = $Advert->id;
return redirect("/property/$id");
}
UploadRequest "Request File"
This is where all the validation rules are stored.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UploadRequest 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()
{
$rules = [
'address' => 'required'
];
$photos = count($this->input('photo'));
foreach(range(0, $photos) as $index) {
$rules['photo.' . $index] = 'min:100';
}
return $rules;
}
}
Upload Form
<form method="POST" action="/property" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group row">
<label for="photo" class="col-md-3 col-form-label text-md-right">Images</label>
<div class="col-md-9">
<input required type="file" class="form-control" name="photo[]" multiple>
</div>
</div>
Your code looks good and I always use foreach but the problem with your loop is you need to invoke your fileinput using the file method :
foreach( $request->file('photo') as $photo )
PS: there is a huge difference between $request->photo and $request->file('photo') so to guess the mime type you should use the file method.
Cheers.
The problem is from your validation!
If you have anything like this:
$this->validate($request, [
'image' => 'required|mimes:jpg,png,jpeg,gif,svg|max:2048',
]);
then replace the validation code to:
'image' => 'required|image|max:2048',
In my case, I had further updates like:
'image' => 'required|image|dimensions:min_width=300,min_height=400,ratio=3/4|max:2048',
Hope this helps. Unfortunately I did not find the reason- why Laravel is not able to retrieve the MIME type and validate the image file uploaded here! This could be because of the another missing PHP extension.
Find all possible validation cases from the doc here.

Laravel parsing Input from a multiple select box not working

This is my pubf in my Controller which handles the request:
public function addPermissionsToRoleHandler($rid, Request $request)
{
$role = Role::find($rid);
dd($request->permissions);
foreach($request->permissions as $perm)
{
$permission = Permission::find($perm->id);
$role->attachPermission($permission);
}
return redirect()->route('showSpecificRole', $rid);
}
This is how I defined my multiple select-box:
{!! Form::select('permissions[]', $permissions, null, array('class' => 'selectpicker show-tick', 'data-live-search' => 'true', 'id' => 'permission_select', 'multiple' => true)) !!}
Why is my dd() returning null? $request->permission is empty. dd($request) only has token_.
I don't have the rep to comment so am posting as an answer. I am not sure, but I think it may be because the Request needs to be the first argument ?

Passing variables to view

I think I might have discovered a bug. This is what I have until now.
Routes.php
Route::get('/{user}/{char_dynasty}/{char_name}/selectedok', array(
'as' => 'char-profile-get',
'uses' => 'CharacterController#getDropDownList'));
Route::post('/user/{user}/{char_dynasty}/{char_name}/selectedok', array(
'as' => 'char-profile-post',
'uses' => 'CharacterController#postDropDownList'));
CharacterController.php
class CharacterController extends BaseController{
public function getDropDownList($user, $char_dynasty, $char_name)
{
if(Auth::check())
{
$user = Auth::user();
return View::make('layout.notification', array(
'user' => $user,
'char_dynasty' => $char_dynasty,
'char_name' => $char_name));
}
else
{
return App::abort(404);
}
}
public function postDropDownList()
{
if (Auth::check())
{
$user = Auth::user();
$char_name = User::find($user->id)->characters()->where('char_name', '=', Input::get('choose'))->first();
return Redirect::route('char-profile-get', array(Session::get('theuser'),
$char_name->char_dynasty,
$char_name->char_name));
}
}
}
profile.blade.php (snippet)
<form action="{{ URL::route('char-profile-post') }}" method="post">
<select name="choose">
<option value="choose">Choose a character</option>
<option> {{ $c_name }} </option>
</select>
<input type="submit" value="Ok">
{{ Form::token() }}
</form>
The error says that $char_dynasty is undefined which is usually used
<option> {{ $char_dynasty }} </option>
I changed to populate the drop down list with another variable to be able to execute the database query $char_name from postDropDownList.
If I do in function getDropDownList, var_dump($char_dynasty); var_dump($char_name) I get the following
string 'Spirescu' (length=8)
string 'Ion' (length=3)
The point is that the parameters in getDropDownList are with the correct data, but are not transfered to the View. What am I doing wrong? I don't know how to access the variables in the View?
I have also tried return View::make('layout.notification', compact('user' , 'char_dynasty' , 'char_name' ));
or
$data = array(
'user' => $user,
'char_dynasty' => $char_dynasty,
'char_name' => $char_name);
return View::make('layout.notification', $data);
I receive the same error. or $data is not defined.

Laravel 4 password reminder: redirection issue

I'm using the Laravel 4 password reminder functionality, as described here: http://four.laravel.com/docs/security#password-reminders-and-reset. In order to generate the token, send the email and create de DB record in the password_reminder table, I use the standard code in my routes file :
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
This code is suppose to send me back to my input form in case of any error (unknown email address for instance). Instead of that, I get a MethodNotAllowedHttpException. The reason is Laravel don't try to send me back to my form URL (which is /password/forgot): he tries to redirect me to /password/remind, in GET, and this route does not exist (of course) in my routes.php file.
I checked the code of the Illuminate\Auth\Reminders\PasswordBroker class, which is responsible of this redirection, and found out this method :
protected function makeErrorRedirect($reason = '')
{
if ($reason != '') $reason = 'reminders.'.$reason;
return $this->redirect->refresh()->with('error', true)->with('reason', $reason);
}
I replaced $this->redirect->refresh() by $this->redirect->back(), and everything is now working as excepted. But as I couldn't find any comment on this bug anywhere, I assume I'm doing something wrong… But I can't find what !
Here is my routes.php file:
Route::get('password/forgot', array('as' => 'forgot', 'uses' => 'SessionsController#forgot'));
Route::post('password/remind', function() {
$credentials = array('email' => Input::get('email'));
return Password::remind($credentials);
});
Route::get('password/reset/{token}', function($token) {
return View::make('sessions.reset')->with('token', $token);
});
Route::post('password/reset/{token}', array('as' => 'reset', 'uses' => 'SessionsController#reset'));
my SessionsController relevant code:
class SessionsController extends BaseController {
[...]
public function forgot() {
return View::make('sessions.forgot');
}
public function reset() {
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'password_confirmation' => Input::get('password_confirmation')
);
Input::flash();
return Password::reset($credentials, function($user, $password) {
$user->password = Hash::make($password);
$user->save();
return Redirect::to('home');
});
}
}
and finally my view code:
{{ Form::open(array('url' => 'password/remind', 'class' => 'form', 'role' => 'form', 'method'=>'post')) }}
<div class="form-group">
{{ Form::label('email', 'E-mail') }}
{{ Form::text('email', '', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
{{ Form::submit("Envoyer", array("class"=>"btn btn-primary")) }}
{{ Form::close() }}
If it is possible, I highly recommend you to upgrade to Laravel 4.1, because it comes with a more flexible (also easier to understand and to work with) solution for password remind/reset.
Check out this example with Laravel 4.1:
https://github.com/laracasts/Laravel-4.1-Password-Resets/blob/master/app/controllers/RemindersController.php

Displaying form validation errors in a template (Symfony)

let's say I have a blog with a module "post".
now I display a post like this: post/index?id=1
in the index-action i generate a new CommentForm and pass it as $this->form to the template and it is being displayed at the bottom of a post (it's just a textfield, nothing special). form action is set to "post/addcomment". How can I display the validation errors in this form? using setTemplate('index') doesn't work because I would have to pass the id=1 to it...
thanks
UPDATE:
here's a sample code:
public function executeIndex(sfWebRequest $request)
{
$post = Doctrine::getTable('Posts')->find($request->getParameter('id'));
$this->post = $post->getContent();
$comments = $post->getComment();
if ($comments->count() > 0)
$this->comments = $comments;
$this->form = new CommentForm();
$this->form->setDefault('pid', $post->getPrimaryKey());
}
public function executeAddComment(sfWebRequest $request) {
$this->form = new CommentForm();
if ($request->isMethod('post') && $request->hasParameter('comment')) {
$this->form->bind($request->getParameter('comment'));
if ($this->form->isValid()) {
$comment = new Comment();
$comment->setPostId($this->form->getValue('pid'));
$comment->setComment($this->form->getValue('comment'));
$comment->save();
$this->redirect('show/index?id='.$comment->getPostId());
}
}
}
and my Comment Form:
class CommentForm extends BaseForm {
public function configure() {
$this->setWidgets(array(
'comment' => new sfWidgetFormTextarea(),
'pid' => new sfWidgetFormInputHidden()
));
$this->widgetSchema->setNameFormat('comment[%s]');
$this->setValidators(array(
'comment' => new sfValidatorString(
array(
'required' => true,
'min_length' => 5
),
array(
'required' => 'The comment field is required.',
'min_length' => 'The message "%value%" is too short. It must be of %min_length% characters at least.'
)),
'pid' => new sfValidatorNumber(
array(
'required' => true,
'min' => 1,
'max' => 4294967295
),
array(
'required' => 'Some fields are missing.'
))
));
}
}
and finally, indexSuccess:
<?php echo $post; ?>
//show comments (skipped)
<h3>Add a comment</h3>
<form action="<?php echo url_for('show/addComment') ?>" method="POST">
<table>
<?php echo $form ?>
<tr>
<td colspan="2">
<input type="submit" />
</td>
</tr>
</table>
</form>
that's it.
If you're using sf 1.4 just put executeAddComments and executeIndex together in one function (executeIndex for example) and you'll be fine. setTemplate won't work here.
Are you using the handleError method in the action ? The id=1 part of your url should not change if inside the handleError method, you do a return sfView::SUCCESS;
UPDATE:
It actually changes, what you need to do is submit the id along with the comment [Which I'm sure you're already doing because a comment that doesn't refer to a post doesn't make much sense], then in your handleError method, instantiate the post object there.
Try to change your form action to
<?php echo url_for('show/addComment?id=' . $post->getId()) ?>
Doing this, your post id parameter should be available even on your post request, and it should work with setTemplate('index') or forward at the end of executeAddComment

Resources