laravel 5.6 with MySql gives Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException error - mysql

There are similar questions under this topic, but none of them gave me an answer. I'm a beginner to laravel and trying to learn by myself.
When I try to connect laravel (version 5.6) with MySql it gives this error.
These are the code lines that working with.
CameraController.php
<?php
namespace App\Http\Controllers;
use App\Camera;
use Illuminate\Http\Request;
class CameraController extends Controller{
public function postCamera(Request $request){
$camera = new Camera();
$camera->email = $request->input('email');
$camera->password = $request->input('password');
$camera->save();
return response()->json([
'message'=>$camera
]);
}
}
CreateCamreasTable.php
public function up(){
Schema::create('cameras', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('email');
$table->text('password');
});
}
api.php
Route::post('/addCamera', ['as' => 'Camera', 'uses' => 'CameraController#postCamera']);
user.php
class User extends Authenticatable{
use Notifiable;
protected $fillable = [
'email',
];
protected $hidden = [
'password',
];
}
I couldn't found out what's wrong with my code..
PS- I'm trying with postman app that supports with sending requests and reading responses. what I'm sending is a json object
{
"email" : "rr#gmal.com",
"password" : "fjf"
}
The error that I receive is

Related

Having problems in the store method Laravel-Eloquent

Been at this for a very long time and I can't get it right. Would be really thankful for some help. Thanks in advance!
Im trying to build a little clone of reddit some learning purpose.
I think these models is correct for what I'm trying to do. Im able to save a Subreddit to DB with user_id. But my problem is that I can't post to the post table since it's telling me it cannot find the subreddits_id column. Im seems like the method im trying to call should be working but it doesnt.
protected $fillable = ['title', 'link','content', 'post_picture', 'user_id', 'subreddit_id'];
//Functions
public function user () {
return $this->belongsTo(User::class);
}
public function subreddit() {
return $this->belongsTo(Subreddit::class);
}
public function comments () {
return $this->hasMany(Comment::class);
}
Above is my Post model
protected $guarded = [];
//Functions
public function user () {
return $this->belongsTo(User::class);
}
public function posts () {
return $this->hasMany(Post::class);
}
public function comments () {
return $this->hasMany(Comment::class);
}
Above is my Subreddit Model
public function posts () {
return $this->hasMany(Post::class);
}
public function subreddit() {
return $this->hasMany(Subreddit::class);
}
public function commments () {
return $this->hasMany(Comment::class);
}
Above is my User model
I think these models is correct for what I'm trying to do. Im able to save a Subreddit to DB with user_id. But my problem is that I can't post to the post table since it's telling me it cannot find the subreddits_id column. Im seems like the method im trying to call should be working but it doesnt.
The Store method looks like this:
public function store(Request $request)
{ $data = request()->validate([
'title' => 'required',
'link' => 'required',
'content' => 'required',
]);
$post = auth()->user()->posts()->create($data);
return redirect('/home');
}
I'm getting this error General error: 1364 Field 'subreddit_id' doesn't have a default value (SQL: insert into posts (title, link, content, user_id, updated_at, created_at) values (awe, ew, we, 2, 2020-04-01 17:41:29, 2020-04-01 17:41:29))
your $data only takes the parameters you specify for validation, But you did not include subreddit_id, It should be like this:
public function store(Request $request)
{ $data = request()->validate([
'title' => 'required',
'link' => 'required',
'content' => 'required',
'subreddit_id' => 'required|exist:subreddits,id'
]);
$post = auth()->user()->posts()->create($data);
return redirect('/home');
}

Can I have a ZF3 MVC Framework Controller with parameters in the constructor?

I have a Zend Framework 3 MVC app with a controller with two end points. Both need to access the same class. It seems like the best way to do this would be to would be to make an instance of this class a property of the controller class like this:
class IndexController extends AbstractActionController
{
/**
* var Utility $utility
*/
protected $utility;
public function __construct(Utility $utility)
{
$this->utility = $utility;
}
public function indexAction()
{
$this->utility->doA('param1');
return new ViewModel();
}
public function otherAction()
{
$results = $this->utility->validateRequest($this->request);
if ($results)
{
return new ViewModel();
}
else
{
throw new Exception('Invalid request');
}
}
}
However, I don't know how to pass paramaters to the constructor since I don't know where Zend Framework "makes" it.
Zend Framework uses a concept called Dependency Injection. This is based on the D in SOLID, dependency inversion. Theory aside, you need to make a custom factory for your controller in modules.config.php. You also need to make a factory for the class calld Utility.
So first of all, you probably made your project with a command similar to composer create-project -sdev zendframework/skeleton-application. If you did that you probably don't have the latest version of Service Manager. See if the file vendor/bin/generate-factory-for-class exists. If not, execute composer update zendframework/zend-servicemanager to add it there.
Now lets make a factory for the utility class. Lets assume its in module/Application/src/Service/Utility.php and has the namespace Application\Service. You just type vendor/bin/generate-factory-for-class Application\\Service\\Utility > module/Application/src/Service/UtilityFactory.php. If you look in that file you can see:
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new Utility();
}
Now lets do the same for the controller with vendor/bin/generate-factory-for-class Application\\Controller\\IndexController > module/Application/src/Controller/IndexControllerFactory.php. Open this factory and see its a little more complex.
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new IndexController($container->get(\Application\Service\Utility::class));
}
$container is your dependency injection container. It executes the __invoke command in these factories when called.
One more thing left to do. you need to edit your module.config.php. Replace the line
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class,
],
],
with
'controllers' => [
'factories' => [
Controller\IndexController::class => Controller\IndexControllerFactory::class,
],
],
Now add the following section to the config:
'service_manager' => [
'factories' => [
Service\Utility::class => InvokableFactory::class,
],
],
Then your controller should work.

Base Table not found on unique value validation in MongoDB with laravel

I'm using laravel 5.3 with jenssegers/laravel-mongodb package for managing mongodb connections.
I want to check every time a user send a request to register a website in my controller if it's unique then let the user to register his/her website domain.
I wrote below code for validation but What I get in result is :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'iranad.seat' doesn't exist (SQL: select count(*) as aggregate from `seat` where `domain` = order.org)
my controller code :
public function store(Request $request) {
$seat = new Seat();
$validator = Validator::make($request->all(), [
'domain' => 'required|regex:/^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/|unique:seat', //validating user is entering correct url like : iranad.ir
'category' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 400);
} else {
try {
$statusCode = 200;
$seat->user_id = Auth::user()->id;
$seat->url = $request->input('domain');
$seat->cats = $request->input('category');
$seat->filter = [];
if($request->input('category') == 'all') {
$obj['cats'] = 'false';
$seat->target = $obj;
} else {
$obj['cats'] = 'true';
$seat->target = $obj;
}
$seat->status = 'Waiting';
$seat->save();
} catch (\Exception $e) {
$statusCode = 400;
} finally {
$response = \Response::json($seat, $statusCode);
return $response;
}
}
}
My Seat Model :
namespace App;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent {
public function getCreatedAtAttribute($value) {
return Carbon::createFromTimestamp(strtotime($value))
->timezone('Asia/Tehran')
->toDateTimeString();
}
}
Obviously The validator is checking if domain is unique in mysql tables which causes this error, How can I change my validation process to check mongodb instead of mysql ?
I solved the problem, The solution is that you should add Moloquent to your model and define database connection :
namespace App\Models;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent
{
protected $collection = 'seat';
protected $connection = 'mongodb';
}

class not found even when it exits on Yii2

I'm making my first application using Yii and I have the next code:
public function actionCreate()
{
$model = new User();
$singUp = new \frontend\models\SingupForm;
if ($singUp->load(Yii::$app->request->post()) && $singUp->save()) {
$model = ModelName::findOne(['id' => $singUP->id]);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
} else {
return $this->render('create', [
'model' => $model,
'singUp' => $singUp
]);
}
}
And I'm having the next error message when I try to go to that method:
Class 'frontend\models\SingupForm' not found
But I have the file saved on the directory as it is showed in the screenshot I attached. Additionally I added all the models folder of the Frontend on the controller I am using:
use Yii;
use \frontend\models;
use common\models\User;
use backend\models\search\UserSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\PermissionHelpers;
So I don't know what I'm doing wrong. Please help
Screenshot
There is a typo in your code.
Please Change frontend\models\SingupForm to frontend\models\SignupForm.

Call to undefined function tests\codeception\unit\models\expect()

I am trying to perform unit testing using the default ContactFormTest inside the yii2 basic application. But it provides me the following error.
E:\xampp\htdocs\news\tests>codecept run unit codeception\unit\models\ContactForm
Test.php
Codeception PHP Testing Framework v2.0.16
Powered by PHPUnit 4.7.7 by Sebastian Bergmann and contributors.
←[1mUnit Tests (1) ←[22m--------------------------------------------------------
------------------------------------
←[35;1mTest contact←[39;22m (tests\codeception\unit\models\ContactFormTest::test
Contact)<pre>PHP Fatal Error 'yii\base\ErrorException' with message &#
039;Call to undefined function tests\codeception\unit\models\expect()'
in E:\xampp\htdocs\news\tests\codeception\unit\models\ContactFormTest.php:46
Stack trace:
#0 [internal function]: yii\base\ErrorHandler->handleFatalError()
#1 {main}</pre>
Below is my ContactFormTest.php
namespace tests\codeception\unit\models;
use app\models\ContactForm;
use Yii;
use yii\codeception\TestCase;
use Codeception\Specify;
use Codeception\Util\Debug;
class ContactFormTest extends TestCase
{
use Specify;
protected function setUp()
{
parent::setUp();
Yii::$app->mailer->fileTransportCallback = function ($mailer, $message) {
return 'testing_message.eml';
};
}
protected function tearDown()
{
unlink($this->getMessageFile());
parent::tearDown();
}
public function testContact()
{
/** #var ContactForm $model */
$model = $this->getMockBuilder('app\models\ContactForm')
->setMethods(['validate'])
->getMock();
$model->expects($this->once())->method('validate')->will($this->returnValue(true));
$model->attributes = [
'name' => 'Tester',
'email' => 'tester#example.com',
'subject' => 'very important letter subject',
'body' => 'body of current message',
];
//Debug::debug($model->contact('admin#example.com'));
//die();
$this->specify('email should be send', function () use ($model) {
expect('ContactForm::contact() should return true', $model->contact('admin#example.com'))->true(); //this throws the error
expect('email file should exist', file_exists($this->getMessageFile()))->true();
});
$this->specify('message should contain correct data', function () use ($model) {
$emailMessage = file_get_contents($this->getMessageFile());
expect('email should contain user name', $emailMessage)->contains($model->name);
expect('email should contain sender email', $emailMessage)->contains($model->email);
expect('email should contain subject', $emailMessage)->contains($model->subject);
expect('email should contain body', $emailMessage)->contains($model->body);
});
}
private function getMessageFile()
{
return Yii::getAlias(Yii::$app->mailer->fileTransportPath) . '/testing_message.eml';
}
}
And unit.suite.yml
# Codeception Test Suite Configuration
# suite for unit (internal) tests.
# RUN `build` COMMAND AFTER ADDING/REMOVING MODULES.
class_name: UnitTester
modules:
config:
Db:
dsn: 'mysql:host=127.0.0.1;dbname=news_tests'
user: 'root'
password: ''
dump: 'tests/_data/dump.sql'
populate: false
cleanup: false
reconnect: true
How to fix this?
Does your IDE recognize the expect function calls inside specify?
If not, then try adding specify and verify to require-dev Composer dependencies as specified in the manual:
"require-dev": {
...
"codeception/specify": "*",
"codeception/verify": "*"
}
And run composer update.
P.S. link with credit for Russian-speaking readers.