I'm trying to insert to database (store function) and I'm getting this error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Method Illuminate\Http\UploadedFile::__toString() must not throw an exception
/home/vagrant/Sites/mySite/vendor/laravel/framework/src/Illuminate/Database/Connection.php
<?php
namespace Illuminate\Database;
use PDO;
use Closure;
use Exception;
use Throwable;
use LogicException;
use RuntimeException; // Highlighted
use DateTimeInterface;
use Illuminate\Support\Arr;
use Illuminate\Database\Query\Expression;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Database\Query\Processors\Processor;
use Doctrine\DBAL\Connection as DoctrineConnection;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Schema\Builder as SchemaBuilder;
use Illuminate\Database\Query\Grammars\Grammar as QueryGrammar;
Arguments
"Method Illuminate\Http\UploadedFile::__toString() must not throw an exception"
store function
/**
* #param Request $request
* #param ReviewProsConsRepository $reviewProsConsRepository
* #param ReviewTextRepository $reviewTextRepository
* #return \Illuminate\Http\RedirectResponse
*/
public function store(Request $request, ReviewProsConsRepository $reviewProsConsRepository, ReviewTextRepository $reviewTextRepository, ReviewLanguageRepository $reviewLanguageRepository, ReviewCurrencyRepository $reviewCurrencyRepository)
{
$review = $this->reviewRepository->create($request->all()); // Here is the error
$this->mutualAction($request, $review->id, $reviewProsConsRepository, $reviewTextRepository, $reviewCurrencyRepository, $reviewLanguageRepository);
return redirect()->route('manager.review.index')->with('message', 'Review criado com sucesso!');
}
-- Edit --
ReviewRepository.php
namespace App\Repositories;
use App\Models\Review;
use Housekeeper\Abilities\Adjustable;
use Housekeeper\Repository;
class ReviewRepository extends Repository
{
use Adjustable;
/**
* Return the name of model that this repository used.
*
* #return string
*/
protected function model()
{
return Review::class;
}
}
I have an image upload that returns the id from the uploaded image to cs_upload_id, but it's getting error and I don't understand why.
Any help is appreciated, thanks.
Not acquainted with the repository package you are using but I'm guessing it's throwing an error because you're simply passing the reviewRepository->create() method $request->all() which will consist of text key pairs which may be fine to process to the DB but will also include Illuminate\Http\UploadedFile which it can figure out how to handle.
What I would recommend is that you prepare the data in a way that the reviewRepository->create() method can understand rather than just passing it the $request->all() and hoping it will handle it just fine.
Hope that makes sense.
Related
I'm trying to write a Laravel PHPUnit test that checks if a mail has been queued after a user was created.
<?php
namespace Tests\Unit\User;
use App\User;
use Tests\TestCase;
use App\Notifications\UserCreated;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserUnitTest extends TestCase
{
use RefreshDatabase;
/**
* check if a user was created in database
*
* #return void
*/
public function testUserCreate()
{
$user = factory(User::class)->create();
$this->assertDatabaseHas('users', [
'email' => $user->email,
'active' => 0,
'activation_token' => $user->activation_token,
'deleted_at' => NULL
]);
}
/**
* check if email was sent after user was created in database
*
* #return void
*/
public function testEmailSentAfterUserCreated()
{
Notification::fake();
// Assert that no notifications were sent...
Notification::assertNothingSent();
$user = factory(User::class)->create();
// Assert a notification was sent to the given users...
Mail::assertQueued(UserCreated::class, 1);
}
}
When I run this test testEmailSentAfterUserCreated it throws the following exception.
There was 1 error:
1) Tests\Unit\User\UserUnitTest::testEmailSentAfterUserCreated
BadMethodCallException: Method Illuminate\Mail\Mailer::assertQueued
does not exist.
/home/vagrant/Projects/endiro/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php:103
/home/vagrant/Projects/endiro/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:245
/home/vagrant/Projects/endiro/tests/Unit/User/UserUnitTest.php:49
The Mail class has been included and I'm sure the arguments are correct but I'm not sure why I'm getting this error.
Use Mail::fake() if you want to assert on Mail::assertQueued(). I was facing the same issue. I forgot to add Mail::fake() in that particular test case.
Notifications does not have an assert queued, it has an assertSentTo().So an example of how it should look. If the notification can be queued, i would think you could use the Queue::fake() to achieve this.
Notification::assertSentTo(
[$user], UserCreated::class
);
I'm trying to send an email using laravel however I keep getting the cannot access empty property error whenever I run my code.
I've done my research on the error and it seems to be usually caused by using a $ before the property name, example $this->$username instead of $this->username. However, that isn't the case in my code.
I can't really tell what's causing it nor do I have great experience in Laravel
Here's my mailable class:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class VerificationMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
$data2 = ['companyName' => $this->data['name'], 'verificationCode' => $this->data['verificationCode']];
return $this->from('noreply#REMOVED.com')
->$this->view('emails.verification', $data2);
}
}
My view is saved in resources/views/emails/verification.blade.php
I saw also that this error can sometimes be caused by using $message as variable name inside the views, however that isn't the case with me. I tried loading the view with a normal route without any mail sending involved and it loaded normally.
Can anyone spot it? Thanks.
You have error here:
return $this->from('noreply#REMOVED.com')
->$this->view('emails.verification', $data2);
Use following instead: (remove second $this->)
return $this->from('noreply#REMOVED.com')
->view('emails.verification', $data2);
This is my first time using events in Laravel/Lumen.
I am actually using Lumen and I am trying to dispatch an instance of Mailable when a new user signs up in order to send an email in the background.
I believe I have set it up right, but I keep getting this error...
Type error: Argument 1 passed to Illuminate\Mail\Mailable::queue() must implement interface Illuminate\Contracts\Queue\Factory, instance of Illuminate\Queue\DatabaseQueue given
I can't actually see within the error message itself where the issue is coming from e.g. there is no line numbers.
However, this is my code...
AuthenticationContoller.php
$this->dispatch(new NewUser($user));
NewUser.php
<?php
namespace App\Mail;
use App\Models\User;
use Illuminate\Mail\Mailable;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class NewUser extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
protected $user;
public function __construct(User $user)
{
$this->user = $user;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('test')->to('test#test.com', 'Test')
->from('test#test.com', 'test')->replyTo('test#test.com', 'test')
->subject('Welcome to the blog!');
}
}
I ran into the same issue. It seems like Lumen and Illuminate/Mailer don't work together all that well.
However I found quite an easy fix in a Github thread.
Basically you just have to create a new service provider in your app/Providers directory.
MailServiceprovider.php
<?php
namespace App\Providers;
use Illuminate\Mail\Mailer;
use Illuminate\Mail\MailServiceProvider as BaseProvider;
class MailServiceProvider extends BaseProvider
{
/**
* Register the Illuminate mailer instance.
*
* #return void
*/
protected function registerIlluminateMailer()
{
$this->app->singleton('mailer', function ($app) {
$config = $app->make('config')->get('mail');
// Once we have create the mailer instance, we will set a container instance
// on the mailer. This allows us to resolve mailer classes via containers
// for maximum testability on said classes instead of passing Closures.
$mailer = new Mailer(
$app['view'], $app['swift.mailer'], $app['events']
);
// The trick
$mailer->setQueue($app['queue']);
// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
foreach (['from', 'reply_to', 'to'] as $type) {
$this->setGlobalAddress($mailer, $config, $type);
}
return $mailer;
});
$this->app->configure('mail');
$this->app->alias('mailer', \Illuminate\Contracts\Mail\Mailer::class);
}
}
And then you just have to register this service provider in your bootstrap/app.php instead of the default one by adding the following line:
$app->register(\App\Providers\MailServiceProvider::class);
I'm trying to call a method in the repository ArticleRepository from my controller ArticleController. However it says :
Undefined method 'afficheArticle'. The method name must start with either findBy or findOneBy!
my Entity Article : (Entity\Article.php)
/**
* Article
*
* #ORM\Table(name="Article", indexes={#ORM\Index(name="I_FK_Article_TypeArticle", columns={"idTypeArticle"})})
* #ORM\Entity(repositoryClass="erp-gkeep\new_erp\gkeepBundle\Repository\ArticleRepository")
*/
class Article
{
my ArticleController (Controller\ArticleController)
/**
* #Route("viewArticle2", name="viewArticle2")
*/
public function listAction2()
{
$data = $this->getDoctrine()->getRepository('gkeepBundle:Article')->afficheArticle();
my ArticleRepository
<?php
/**
* Created by PhpStorm.
*/
namespace gkeepBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ArticleRepository extends EntityRepository
{
public function afficheArticle(){
$em=$this->getEntityManager();
$query = $em->createQuery(
'SELECT a.reference, a.designationfr, a.designationen, a.plan, a.url, a.datecreation, a.idtypearticle
FROM gkeepBundle:Article a
'
);
$articles = $query->getArrayResult();
return $articles;
}
}
if someone can help me please ! I'm pretty sure it's a stupid error :/
The value of repositoryClass in your mapping annotation needs to be the namespace + class name of your repository, it looks like you've maybe added some of the directory structure as well. - actually isn't a valid character in a PHP namespace, so the value you've got now definitely isn't right.
Try
#ORM\Entity(repositoryClass="gkeepBundle\Repository\ArticleRepository")
For reference: when this classname is not valid, Doctrine falls back to the default repository - this is what's throwing the error you're seeing.
Warning: This question is Laravel 4 specific.
I've been using Facades in my controllers before. Therefore I know the code is working. Now I need to introduce dependency injection for various reasons.
After refactoring the controller I get following error:
Illuminate \ Container \ BindingResolutionException
Unresolvable dependency resolving [Parameter #0 [ $name ]].
I can't figure out where the problem is. The Error message seems cryptic to me and I don't understand it. (I don't see any problem with my __constructor parameters since I've registered the binding for the HelpersInterface)
Here are the important parts of my code:
File: app/start/global.php
<?php
// ...
App::bind('Acme\Interfaces\HelpersInterface', 'Acme\Services\Helpers');
File: composer.json
// ...
"autoload": {
// ...
"psr-0": {
"Acme": "app/"
}
},
// ...
File: app/Acme/Controllers/BaseController.php
<?php namespace Acme\Controllers;
use Carbon\Carbon;
use Controller;
use Illuminate\Foundation\Application as App;
use Illuminate\View\Factory as View;
use Acme\Interfaces\HelpersInterface as Helpers;
use Illuminate\Http\Response;
class BaseController extends Controller {
/**
* #var \Illuminate\Foundation\Application
*/
private $app;
/**
* #var \Carbon\Carbon
*/
private $carbon;
/**
* #var \Illuminate\View\Factory
*/
private $view;
/**
* #var \Acme\Interfaces\HelpersInterface
*/
private $helpers;
function __construct(App $app, Carbon $carbon, View $view, Helpers $helpers)
{
$this->app = $app;
$this->carbon = $carbon;
$this->view = $view;
$this->helpers = $helpers;
$lang = $this->app->getLocale();
$now = $this->carbon->now();
$this->view->share('lang', $lang);
$this->view->share('now', $now);
}
/**
* Missing Method
*
* Abort the app and return a 404 response
*
* #param array $parameters
* #return Response
*/
public function missingMethod($parameters = array())
{
return $this->helpers->force404();
}
}
File: app/Acme/Services/Helpers.php
<?php namespace Acme\Services;
use Illuminate\Config\Repository as Config;
use Illuminate\Database\Connection as DB;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector as Redirect;
use Illuminate\Session\Store as Session;
use Illuminate\Support\Facades\Response;
use Illuminate\Translation\Translator as Lang;
use Illuminate\View\Factory as View;
use Acme\Interfaces\MockablyInterface;
use Monolog\Logger as Log;
class Helpers implements HelpersInterface {
// ...
public function __construct(
Config $config,
Lang $lang,
View $view,
MockablyInterface $mockably,
Log $log,
Request $request,
Session $session,
DB $db,
Redirect $redirect,
Response $response
) {
// ...
}
// ...
}
File: app/Acme/Providers/HelpersServiceProvider.php
<?php namespace Acme\Providers;
use Illuminate\Support\ServiceProvider;
use Acme\Services\Helpers;
class HelpersServiceProvider extends ServiceProvider {
private $db;
private $defaultDbConnection;
protected function init()
{
$this->db = $this->app['db'];
$this->defaultDbConnection = $this->db->getDefaultConnection();
}
public function register()
{
$this->init();
$this->app->bind('helpers', function ()
{
return new Helpers(
$this->app['config'],
$this->app['translator'],
$this->app['view'],
$this->app['mockably'],
$this->app->make('log')->getMonolog(),
$this->app['request'],
$this->app['session.store'],
$this->db->connection($this->defaultDbConnection),
$this->app['redirect'],
$this->app['Illuminate\Support\Facades\Response']
);
});
}
For me it was just a matter of running
php artisan optimize:clear
It seems your Acme\Services\Helpers constructor takes a $name parameter, but is not type hinted.
Laravel's IoC is not magic. If your don't provide a type hint for every parameter, the IoC container has no way of knowing what to pass in.
Make sure you use Illuminate\Http\Request; on top of the file instead of any other http import like this
use Illuminate\Http\Request;
THANK ME LATER!
Got it fixed. All the tutorials about dependency injection were referring to concrete implementations of interfaces so that I thought that's the way to go about it. Joseph Silber's answer got me on the right track.
The trick is to bind the Interface to the binding of the ServiceProvider like shown below. That way Laravel will know how to instantiate the Helpers service.
File: app/start/global.php
<?php
// ...
App::bind('Acme\Interfaces\HelpersInterface', 'helpers');