Can't insert data into Mongodb in Laravel - mongodb

Let me explain all the step that I followed. I am using LAMP.
First of all I installed Laravel , MongoDB and jenssegers/laravel-mongodb pakage. For this I followed this link.
After that I create database, table and insert data using terminal with all success.
Next step is to integrate mongodb with laravel so I add MongoDB connection detail in app/config/database.php file.
'mongodb' => [
'driver' => 'mongodb',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', 27017),
'database' => env('DB_DATABASE', 'usedgoodstore'),
],
'default' => env('DB_CONNECTION', 'mongodb'),
Up to this point all work fine.
Next I create route, view, controller, model file and insert code.
routes/web.php
Route::post('/index', 'UserController#index');
welcome.blade.php
<form action="{{ url('/index') }}" method="post">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br><br>
<input type="submit" value="Submit">
</form>
UserController.php
<?php
namespace App\Http\Controllers;
use App\Model\User;
use Illuminate\Http\Request;
class UserController extends Controller{
protected $user;
public function __construct(User $user){
$this->user = $user;
}
public function Index(Request $request){
$data = array('firstname' => $request['firstname'], 'lastname' => $request['lastname']);
$user = $this->user->PostUser($data);
return response()->json($user,200);
}
}
User.php (model file)
<?php
namespace App\Model;
use Jenssegers\Mongodb\Eloquent\Model as Moloquent;
use DB; // if I use and not use this statement and then getting different errors
class User extends Moloquent {
protected $connection = 'mongodb';
protected $collection = 'user';
public function PostUser($data){
$insertData = DB::collection('user')->insert($data); // I'm getting error on this line.
if($insertData){
return true;
}
}
}
Error I'm getting is :
FatalThrowableError in User.php line 25:
Class 'App\Model\DB' not found
If I add use db in User.php (model file) I'm getting below error.
FatalThrowableError in DatabaseManager.php line 317:
Call to undefined method Illuminate\Database\MySqlConnection::collection()
What have I missed?

First open app/config/database.php file and make your mongodb default database.
'default' => 'mongodb',
and if you don't want mongodb as a default database connection then you can do following thing.
public function PostUser($data){
$insertData = DB::connection('mongodb')->collection('user')->insert($data); // I'm getting error on this line.
if($insertData){
return true;
}

Related

Troubleshooting CakePHP form submission

I recently set up the ability to tag posts on my site. I had everything working fine. Then as I was wrapping up I tested all my admin side forms again. The Add Tag form no longer does anything. It doesn't even flash an error or redirect after submission. The page just reloads at the same URL. The only changes to the site I have made since initial testing was move the forms to the admin side of the dev site. Here is some code to hopefully reveal what the mystery is. Also my edit tag form is doing similar thing. It has no flash message but redirects back to the index, like its supposed to but with no changes made to the tag. Ill include the edit code as well.
Add.ctp in src/Template/Admin/Tags/Add.ctp
<div class="tags form large-9 medium-8 columns content">
<?= $this->Form->create($tag) ?>
<div class="form-group">
<fieldset>
<h1 class="page-header">New Tag</h1>
<?php
echo $this->Form->input('name', ['class' => 'form-control']);
?>
</fieldset>
</div>
<?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary']) ?>
<?= $this->Form->end() ?>
</div>
Here is my Add funciton in my TagsController:
public function add()
{
$this->viewBuilder()->layout('admin');
$tag = $this->Tags->newEntity();
if ($this->request->is('post')) {
$tag = $this->Tags->patchEntity($tag, $this->request->data);
if ($this->Tags->save($tag)) {
$this->Flash->success(__('The tag has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The tag could not be saved. Please, try again.'));
}
$this->set(compact('tag'));
$this->set('_serialize', ['tag']);
}
Here is my Edit funciton in my TagsController:
public function edit($id = null)
{
$this->viewBuilder()->layout('admin');
$tag = $this->Tags->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$tag = $this->Tags->patchEntity($tag, $this->request->data);
if ($this->Tags->save($tag)) {
$this->Flash->success(__('The tag has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The tag could not be saved. Please, try again.'));
}
$this->set(compact('tag'));
$this->set('_serialize', ['tag']);
}
Edit.ctp in src/Template/Admin/Tags/Edit.ctp
<div class="tags form large-9 medium-8 columns content">
<?= $this->Form->create($tag) ?>
<div class="form-group">
<fieldset>
<h1 class="page-header">Edit Tag</h1>
<?php
echo $this->Form->input('name', array('class' => 'form-control'));
?>
</fieldset>
</div>
<?= $this->Form->button(__('Submit'), ['class' => 'btn btn-primary']) ?>
<?= $this->Form->end() ?>
</div>
Just as a side note. I started getting errors when creating a new post as well.
General error: 1364 Field 'section_id' doesn't have a default value
I did go into my DB and give the field a default value. But then when I fill out the form for a new post again, the error just moves to the next table column. I am assuming they are some how related since they popped up at the same time and because tags and posts are related to each other.
TagsTable:
class TagsTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->table('tags');
$this->displayField('name');
$this->primaryKey('id');
$this->hasMany('PostsTags', [
'foreignKey' => 'tag_id'
]);
}
/**
* Default validation rules.
*
* #param \Cake\Validation\Validator $validator Validator instance.
* #return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->requirePresence('name', 'create')
->notEmpty('name');
return $validator;
}
}
Tags Entity:
class Tag extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* #var array
*/
protected $_accessible = [
'*' => false,
'id' => false
];
}
When I place <?php debug($tag); ?> into my add.ctp view this is the out put it gives me:
object(App\Model\Entity\Tag) {
'[new]' => true,
'[accessible]' => [],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'Tags'
}
Again, in question always post debug pathEntity output, in your case debug($tag), also Tag Entity, your validation code, and how looks your db tags table.
Answer:
General error: 1364 Field 'section_id' doesn't have a default value
This means that you have not passed a value for this field.
You can change that table field to accept null or empty value and/or set default if not passed from application, or make validation in your TagsTable to be sure if submitted data valid before send to db.
After question updated:
protected $_accessible = [
'*' => false, <---- should be true
'id' => false
];
This means that all fields except id are accessible

Trying to get property of non-object - Laravel Form

I am creating a form with a many-many relationship. I have a posts table and an activities table. There is a many to many link using pivot table. I am creating a form to add one or more activities to the posts. I am receiving an 'ErrorException' - Trying to get property of non-object. I cannot understand why this is not working.
I would be grateful for any assistance you can offer me.
My relevant code is below.
//Posts/create.blade.php
{!!Form::open(['action' => 'PostController#store','method' => 'POST', 'class'=>'form-group'])!!}
{{Form::bsText('title','',['placeholder' => 'Trip Name'])}}
{{Form::bsTextarea('body','',['placeholder' => 'Trip Description'])}}
{{Form::bsSubmit('submit')}}
{{Form::label('activities', 'Activity:') }}
<select class="form-control select2-multi" name="activities" multiple="multiple">
#foreach($activities as $activity)
<option value="{{ $activity->id }}">{{ $activity->activity_name}}
</option>
#endforeach
</select>
{!! Form::close() !!}
// PostsController
public function create()
{
$activities = Activity::all();
return view('posts.create')->withActivities($activities);
$posts = Post::all();
}
public function store(Request $request)
{
// Create a new post using the request data
// Save it to the database
$this->validate(request(), [
'title' => 'required',
'body' => 'required',
]);
$post = Post::create([
'title' =>request('title'),
'body' =>request('body'),
'user_id' => auth()->id(),
'activity_id' => id()
]);
// And then redirect to somewhere in application
return redirect()->route('posts.show', $post->id);
}
This error throw only when you have empty variable but you point in blade file to render / display for browser. Or if you retrieve records from DB then add findOrFail in query to prevent those kind of issues. Thank you.

Validating a form that is not ‘add’ or ‘edit’ in Cakephp3.3

I’m learning Cakephp3.3 and have run into a problem trying to validate a form prior to saving.
I created a new form in ‘src/Template/Users’ called ‘register.ctp’ and added an action called ‘register’ in ‘src/Controller/UsersController’.
I want to validate form submissions before saving but can’t figure out how to make this work.
FWIW, pre-save validation works perfectly for the ‘add’ and ‘edit’ forms, though I think this happens by default in Cakephp3.
Is there a way to make these same validation rules apply for the ‘register’ form?
FYI, the 'register' action is actually updating an existing user record previously created for an anonymous user.
Here's the controller action:
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Event\Event;
class UsersController extends AppController
{
//<snipped methods>
public function register()
{
if($this->request->session()->read('Auth.User'))
{
$id = $this->request->session()->read('Auth.User.id');
if ($this->request->is(['patch', 'post', 'put']))
{
$user = $this->Users->get($id, [
'contain' => []
]);
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user))
{
$this->Flash->success(__('Your free trial period has started.'));
return $this->redirect("/Home/index");
}
else
{
$this->Flash->error(__('We were unable to start your trial. Please, try again.'));
}
}
}
else
{
$this->Flash->error(__('Your demo session has expired. Please start again.'));
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
}
Here's the UsersTable Model with the validation rules:
<?php
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class UsersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
}
public function validationDefault(Validator $validator)
{
$validator
->integer('id')
->allowEmpty('id', 'create');
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->requirePresence('lastname')
->notEmpty('lastname')
->add('lastname', 'minlength',['rule' => ['minlength', 1]]);
$validator
->integer('status')
->requirePresence('status', 'create')
->notEmpty('status');
$validator
->add('role', 'inList', [
'rule' => ['inlist', ['admin','author','subscriber']],
'message' => 'Please enter a valid role.'
]);
$validator
->requirePresence('referer', 'create')
->allowEmpty('referer');
$validator
->integer('plan_id')
->requirePresence('plan_id', 'create')
->notEmpty('plan_id');
return $validator;
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
}
And here's the register.ctp form:
<div class="users form large-12 columns ">
<?= $this->Form->create() ?>
<fieldset>
<legend><?= __('Sign Up For Your No-Risk Free Trial!') ?></legend>
<?= $this->Form->input('firstname'); ?>
<?= $this->Form->input('lastname'); ?>
<?= $this->Form->input('email'); ?>
<?= $this->Form->input('password'); ?>
</fieldset>
<?= $this->Form->button(__('Start My Free Trial Now')) ?>
<?= $this->Form->end() ?>
</div>
Any help would be greatly appreciated!
if you want to save then the Default validation rules will be apply. if you don't want to apply the default rule then just add the 'validate' => false param
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => false])
if you want to custom validation rule only for register options then need to create new function in your TABLE
class UsersTable extends Table
{
public function validationRegister($validator)
{
$validator
->email('email')
->requirePresence('email')
->notEmpty('An email address is required.');
$validator
->requirePresence('password')
->notEmpty('A password is required.');
$validator
->requirePresence('firstname')
->notEmpty('firstname')
->add('firstname', 'minlength',['rule' => ['minlength', 1]]);
return $validator;
}
}
Now set the 'validate' => 'register' param in your controller newEntity or patchEntity Funciton
$user = $this->Users->patchEntity($user, $this->request->data,['validate' => 'register'])

trying to send email with laravel, get an error. What does this mean?

I'm trying to send email with laravel, get an error. What does this mean?
stream_set_blocking() expects parameter 1 to be resource, null given
Edit: Mail code.
controller:
public function postSubmit(Request $request)
{
Mail::send('emails.contact', ['data' => $request->all()], function ($m) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to('xxxxx', 'xxxx')->subject('Contact Form Submitted');
});
}
Routes:
Route::get('/contact', 'ContactController#index');
Route::post('/contact/submit', 'ContactController#postSubmit');
View:
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST" action="{{ url('contact/submit') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
Send view:
<strong>You have a new feedback from contact page!</strong>
<p><strong>Name: </strong> {{$data['name']}}</p>
<p><strong>Email: </strong> {{$data['email']}}</p>
<p><strong>Message: </strong> {{$data['message']}}</p>
Edit2: disable_functions: "phpinfo, system, exec, passthru, proc_open, shell_exec, popen, setlimit, mysql_pconnect, stream_socket_client"
These functions are disabled by the host. (They won't enable them due security reasons). I've been informed that I can use mail(). How does that work exactly?! (smtp, username, password, etc..)
This is how I managed to get laravel to send an email.
Yes, of course. Here's the solution that I used in order to configure email for laravel.
indexmail.php, root folder
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$query = $_POST['message'];
$email_from = $name.'<'.$email.'>';
$to="your-email#your-domain.com";
$subject="Enquiry!";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: ".$email_from."\r\n";
$message="
Name:
$name
<br>
Email-Id:
$email
<br>
Message:
$query
";
if(mail($to,$subject,$message,$headers))
header("Location:../contact.php?msg=Successful Submission! Thankyou for contacting us.");
else
header("Location:../contact.php?msg=Error To send Email !");
//contact:-your-email#your-domain.com
}
?>
routes.php
Route::post('/contact/submit', 'ContactController#postSubmit');
config/mail.php
'from' => ['address' => 'Sender#email.com', 'name' => 'MyName'],
'pretend' => false,
email view.
<strong>You have a new feedback from contact page!</strong>
<p><strong>Name: </strong> {{$data['name']}}</p>
<p><strong>Email: </strong> {{$data['email']}}</p>
<p><strong>Message: </strong> {{$data['message']}}</p>
contact form.
<form role="form" id="feedbackForm" data-toggle="validator" data-disable="false" method="POST"
action="{{ url('contact/submit') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
app/Http/Requests/ContactFormRequest.php
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactFormRequest extends Request
{
/**
* 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()
{
return [
'name' => 'required',
'email' => 'required|email',
'message' => 'required',
];
}
}
app/User.php
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Let me know if it works! original refference

Create a form for uploading images

I want to let users upload images from their drives. Searching around the net, here's what I've found :
The form :
class ImageForm extends BaseForm
{
public function configure()
{
parent::setUp();
$this->setWidget('file', new sfWidgetFormInputFileEditable(
array(
'edit_mode'=>false,
'with_delete' => false,
'file_src' => '',
)
));
$this->setValidator('file', new sfValidatorFile(
array(
'max_size' => 500000,
'mime_types' => 'web_images',
'path' => '/web/uploads/assets',
'required' => true
//'validated_file_class' => 'sfValidatedFileCustom'
)
));
}
}
the action :
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
if ($this->form->isValid())
{
//...what goes here ?
}
}
the template :
<form action="<?php echo url_for('#images_add') ?>" method="POST" enctype="multipart/data">
<?php echo $form['file']->renderError() ?>
<?php echo $form->render(array('file' => array('class' => 'file'))) ?>
<input type="submit" value="envoyer" />
</form>
Symfony doesn't throw any errors, but nothing is transfered. What am I missing ?
Youre missing an impotant part which is binding the the values to the form:
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
// you need to bind the values and files to the submitted form
$this->form->bind(
$request->getParameter($this->form->getName())
$request->getFiles($this->form->getName())
);
// then check if its valid - if it is valid the validator
// should save the file for you
if ($this->form->isValid())
{
// redirect, render a different view, or set a flash message
}
}
}
However, you want to make sure you set the name format for your form so you can grab a the values and files in the fashion... In your configure method you need to call setNameFormat:
public function configure()
{
// other config code
$this->widgetSchema->setNameFormat('image[%s]');
}
Also in configure you dont need to call parent::setUp()... That is called automatically and is actually what invokes the configure method.
LAstly, you ned to have to correct markup - your emissing the form name from your tag:
<form action="<?php echo url_for('#images_add') ?>" name="<?php echo $form->getName() ?>" method="POST" enctype="multipart/data">
Personally I like to use the form object to generate this as well as it looks cleaner to my eyes:
<?php echo $form->renderFormTag(
url_for('#images_add'),
array('method' => 'post') // any other html attriubutes
) ?>
It will work out the encoding and name attributes based on how youve configured the form.