Laravel - Unique rules validation - getMessages does not exist - validation

I have a simple quiz app I'm writing where there is a series of challenges (Easy, Medium, Hard), each with their own questions.
The questions to be added should be unique.
I have the following code to "store" the data
$v = ChallengeQuests::validate(Input::all());
if ( $v->passes() ) {
print 'validate passed';
$record = ChallengeQuests::create(array(
'challenge_id'=> (int) Input::get('challenge_id'),
'question_id'=> (int) Input::get('question_id')
));
$record->save();
return redirect()->to($url['redirects_to']);
} else {
print 'error';
print_r($v->getMessages());
return Redirect::to('/')->withErrors($v->getMessages());
}
In my model I have a validation method
// model
class ChallengeQuests extends Model
{
//
protected $table = 'challengequests';
protected $fillable=[
'challenge_id',
'question_id'
];
public static function validate($input) {
$rules = array(
'challenge_id' => 'Required|Integer',
'question_id' => 'Required|Integer|Unique:questions,id'
);
return Validator::make($input, $rules);
}
}
But when I run my code, Laravel complains
BadMethodCallException in Validator.php line 3016:
Method [getMessages] does not exist.
I'm wanting it so that the question_id is unique.
What am I doing wrong?
Edit:
I am using:
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
Stack trace:
BadMethodCallException in Validator.php line 3016:
Method [getMessages] does not exist.
in Validator.php line 3016
at Validator->__call('getMessages', array()) in ChallengeQuestionsController.php line 78
at ChallengeQuestionsController->store(object(Request))
at call_user_func_array(array(object(ChallengeQuestionsController), 'store'), array(object(Request))) in Controller.php line 80
at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(ChallengeQuestionsController), object(Route), 'store') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(ChallengeQuestionsController), object(Route), object(Request), 'store') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\ChallengeQuestionsController', 'store') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 102
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 53
at require_once('/Applications/XAMPP/xamppfiles/htdocs/laravel/scquiz/public/index.php') in server.php line 21

The correct method used to get the validation messages is not getMessages() it's messages(), so your code should look like this:
return Redirect::to('/')->withErrors($v->messages());
Also if you're using Laravel 5, you might want to look into using Form Request Validation which does the same thing you're trying to achieve but in a nicer way, and handles the validation on a different layer, taking care of passing the errors and page redirection for you.
By using a Form Request in your case, the controller method would be reduced to this:
public function store(ChallangeQuestsFormRequest $request)
{
ChallengeQuests::create($request->only('challenge_id', 'question_id'));
return redirect()->to($url['redirects_to']);
}
Since the rules and validation as well as redirection in case of an error, would be handled by the ChallangeQuestsFormRequest class. Also, using create to create a model entry will automatically save the entry, so there's no need to use save on the result of create.

Related

NotFoundHttpException in Handler.php line 131: laravel

For some reason I'm getting this error
NotFoundHttpException in Handler.php line 131: No query results for model [App\Modules\Menus\Models\Menu].
I shouldn't be getting this error since I'm not referencing the menu model at all in my dashboard function.
I've done route:clear and route:cache without any success.
Here is my CustomersController
namespace App\Modules\Customers\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Modules\Menus\Models\Menu;
use App\Modules\Customers\Models\Customer;
use DB;
use Validator;
Use Mail;
use Auth;
class CustomersController extends Controller
{
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required'
]);
if(auth('customer_admin')->attempt(array('email' => $request->input('email'), 'password' => $request->input('password'))))
{
if(auth()->guard('customer_admin')->user()->is_activated == '0')
{
$this->logout();
return back()->with('error', 'Please activate your account.');
}
return redirect()->route('dashboard');
}else{
return back()->with('error', 'Your email/password combination is wrong.');
}
}
public function dashboard()
{
echo "dashboard";
}
}
My web.php routes
Route::get('/signup', [
'uses' => 'CustomersController#signup',
'as' => 'customer.signup'
]);
Route::post('/signup', [
'uses' => 'CustomersController#postSignup',
'as' => 'post.signup'
]);
Route::get('customer/activation/{token}', [
'uses' => 'CustomersController#customerActivation',
'as' => 'activation',
]);
Route::post('/login', [
'uses' => 'CustomersController#login',
'as' => 'login'
]);
// CUSTOMER LOGIN
Route::get('/dashboard', [
'uses' => 'CustomersController#dashboard',
'as' => 'dashboard'
]);
Route::get('/logout', [
'uses' => 'CustomersController#logout',
'as' => 'logout'
]);
The full stack trace
in Handler.php line 131
at Handler->prepareException(object(ModelNotFoundException)) in Handler.php
line 109
at Handler->render(object(Request), object(ModelNotFoundException)) in
Handler.php line 47
at Handler->render(object(Request), object(ModelNotFoundException)) in
Pipeline.php line 82
at Pipeline->handleException(object(Request),
object(ModelNotFoundException)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
VerifyCsrfToken.php line 65
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
StartSession.php line 64
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php
line 102
at Pipeline->then(object(Closure)) in Router.php line 561
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php
line 520
at Router->dispatchToRoute(object(Request)) in Router.php line 498
at Router->dispatch(object(Request)) in Kernel.php line 174
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in
Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
ValidatePostSize.php line 27
at ValidatePostSize->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php
line 102
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 54
1/2 ModelNotFoundException in Builder.php line 395: No query results for
model [App\Modules\Menus\Models\Menu].
in Builder.php line 395
at Builder->firstOrFail() in OpenController.php line 52
at OpenController->content('dashboard')
at call_user_func_array(array(object(OpenController), 'content'), array('id'
=> 'dashboard')) in Controller.php line 55
at Controller->callAction('content', array('id' => 'dashboard')) in
ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(OpenController),
'content') in Route.php line 204
at Route->runController() in Route.php line 160
at Route->run() in Router.php line 559
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php
line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
VerifyCsrfToken.php line 65
at VerifyCsrfToken->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
StartSession.php line 64
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php
line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php
line 102
at Pipeline->then(object(Closure)) in Router.php line 561
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php
line 520
at Router->dispatchToRoute(object(Request)) in Router.php line 498
at Router->dispatch(object(Request)) in Kernel.php line 174
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request)) in
Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
TransformsRequest.php line 30
at TransformsRequest->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
ValidatePostSize.php line 27
at ValidatePostSize->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in
CheckForMaintenanceMode.php line 46
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in
Pipeline.php line 148
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Pipeline.php
line 53
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php
line 102
at Pipeline->then(object(Closure)) in Kernel.php line 149
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 116
at Kernel->handle(object(Request)) in index.php line 54
I see:
Route::post('/login', [
'uses' => 'CustomersController#login',
'as' => 'login'
]);
How about the respective:
Route::get('/login', [
'uses' => 'CustomersController#loginPage',
'as' => 'page.login'
]);
You could also redirect the user to login route when they hit dashboard route.
public function dashboard()
{
return redirect("login"); //redirect to login page
}
As an aside, re-arrange your use statements to:
use DB;
Use Mail;
use Auth;
use Validator;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Modules\Menus\Models\Menu;
use App\Http\Controllers\Controller;
use App\Modules\Customers\Models\Customer;
This has nothing to do with the error you are having, its just a good practice. My answer to your question is in your routes file like shown above.
I assume you're using Laravel 5.2 given the routes file named web.php
Your routes are loaded into RouteServiceProvider and it assumes all the controllers are located under namespace App\Http\Controllers
I've noticed that your controller is under App\Modules\Customers\Http\Controllers namespace.
So the correct way to define routes for it is specifying the complete namespace to it. See the example:
<?php
Route::get('/signup', [
'uses' => '\App\Modules\Customers\Http\Controllers\CustomersController#signup',
'as' => 'customer.signup'
]);
Another (and better) way is to define a dedicated RouteServiceProvider for each "module" of your application. Check your default provider under app/Providers/RouteServiceProvider.php file to know how it works.

BadMethodCallException in Builder.php line 2405: Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()

When I use auth()->user()->roles() with tinker it works without any problem but when I use it on the web page itself I get:
BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()
What does this mean, what could be the reason for this? Here is the related model:
class User extends Authenticatable
{
public function roles(){
return Role::where('id', 6);
}
}
I am using laravel 5.2 and the complete error is like below.
PS: I guess the problem has something to do with the way I am using it in other parts of the site. Thats why it works on tinker. the other parts look like they require the result of the form of Relation obj which I can't provide after the where query.
BadMethodCallException in Macroable.php line 74:
Method addEagerConstraints does not exist.
in Macroable.php line 74
at Collection->__call('addEagerConstraints', array(array(object(User), object(User)))) in Builder.php line 667
at Collection->addEagerConstraints(array(object(User), object(User))) in Builder.php line 667
at Builder->loadRelation(array(object(User), object(User)), 'roles', object(Closure)) in Builder.php line 645
at Builder->eagerLoadRelations(array(object(User), object(User))) in Builder.php line 322
at Builder->get()
at call_user_func_array(array(object(Builder), 'get'), array()) in Relation.php line 343
at Relation->__call('get', array()) in Relation.php line 113
at BelongsTo->get() in Relation.php line 113
at Relation->getEager() in Builder.php line 676
at Builder->loadRelation(array(object(Comment), object(Comment), object(Comment)), 'user', object(Closure)) in Builder.php line 645
at Builder->eagerLoadRelations(array(object(Comment), object(Comment), object(Comment))) in Builder.php line 322
at Builder->get() in ModuleController.php line 27
at ModuleController->main(array())
at call_user_func_array(array(object(ModuleController), 'main'), array(array())) in Container.php line 507
at Container->call(array(object(ModuleController), 'main'), array(array())) in Container.php line 602
at Container->callClass('\App\Modules\Preview_coupons_comments\Controllers\ModuleController#main', array(array()), null) in Container.php line 502
at Container->call('\App\Modules\Preview_coupons_comments\Controllers\ModuleController#main', array(array())) in Facade.php line 219
at Facade::__callStatic('call', array('\App\Modules\Preview_coupons_comments\Controllers\ModuleController#main', array(array()))) in PageController.php line 220
at App::call('\App\Modules\Preview_coupons_comments\Controllers\ModuleController#main', array(array())) in PageController.php line 220
at PageController->getPageByName()
at call_user_func_array(array(object(PageController), 'getPageByName'), array()) in Controller.php line 80
at Controller->callAction('getPageByName', array()) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(PageController), object(Route), 'getPageByName') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(PageController), object(Route), object(Request), 'getPageByName') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), 'App\Http\Controllers\PageController', 'getPageByName') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 724
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckActive.php line 23
at CheckActive->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckActive), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 64
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 726
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Debugbar.php line 51
at Debugbar->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Debugbar), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54
at require_once('/Users/skeletor/Sites/project/public/index.php') in server.php line 21
this is the dd of the normal relation $this->belongsToMany(Role::class);
BelongsToMany {#971 ▼
#table: "role_user"
#foreignKey: "user_id"
#otherKey: "role_id"
#relationName: "roles"
#pivotColumns: []
#pivotWheres: []
#pivotWhereIns: []
#pivotCreatedAt: null
#pivotUpdatedAt: null
#query: Builder {#996 ▶}
#parent: User {#319 ▶}
#related: Role {#812 ▶}
}
and this is the modified return Role::where('id', 6); one
Builder {#812 ▼
#query: Builder {#317 ▶}
#model: Role {#997 ▶}
#eagerLoad: []
#macros: []
#onDelete: null
#passthru: array:11 [▶]
#scopes: []
#removedScopes: []
}
they look quite different and this may the reason.
As #SimonSvensson asked here is my Comment model
class Comment extends Model
{
/**
* Fields that can be mass assigned.
*
* #var array
*/
protected $fillable = ['active', 'user_id', 'text', 'url'];
/**
* Comment morphs to models in commentable_type.
* Get all of the owning commentable models.
*
* #return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function commentable()
{
// morphTo($name = commentable, $type = commentable_type, $id = commentable_id)
// requires commentable_type and commentable_id fields on $this->table
return $this->morphTo();
}
/**
* Query scope ofWebsite.
*
* #param \Illuminate\Database\Eloquent\Builder
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOfWebsite($query)
{
return $query->where(function($q){
$q->whereNull('commentable_id')->whereNull('commentable_type');
});
}
/**
* Comment belongs to User.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
// belongsTo(RelatedModel, foreignKey = user_id, keyOnRelatedModel = id)
return $this->belongsTo(User::class);
}
}
It looks like you're trying to eager-load the User.roles relation, but it isn't a proper relation, it's just a method that invokes a call to Role::where(...). Relation methods are usually returning something like $this->hasMany(Role::class).

Decrypt exception when calling a model with $with

I have 3 models,
User, Host and URL
Basically, URL has a host_id field, so that I could relate the 2 models together.
Here are my models:
User Model (user_urls is just a pivot table containing user_id and url_id)
class User extends Authenticatable
{
... irrelevant codes here...
public function urls(){
return $this->belongsToMany('\App\Models\SEO\Url', 'user_urls', 'user_id', 'url_id')->withTimestamps();
}
}
Host model:
class Host extends Model
{
protected $fillable = [
'friendly_name',
'hosting_cost',
'login_url',
'username', //encrypted field
'password' //encrypted field
];
...some irrelevant codes here...
-- MUTATORS/ACCESSORS---
public function setPasswordAttribute($value){
$this->attributes['password'] = \Crypt::encrypt($value);
}
public function getPasswordAttribute($value){
return $this->attributes['password'] = \Crypt::decrypt($value);
}
...
}
URL model:
class Url extends Model
{
protected $table = 'urls';
protected $with = ['host'];
public function host(){
return $this->belongsTo('\App\Models\SEO\Host', 'host_id');
}
}
Now, when I try to do this on a controller,
return $this->user->urls();
It returns an exception
in BaseEncrypter.php line 44
at BaseEncrypter->getJsonPayload('password') in Encrypter.php line 96
at Encrypter->decrypt('password') in Facade.php line 218
at Facade::__callStatic('decrypt', array('password')) in Host.php line 69
at Crypt::decrypt('password') in Host.php line 69
at Host->getPasswordAttribute('password') in Model.php line 2782
at Model->mutateAttribute('password', 'password') in Model.php line 2794
at Model->mutateAttributeForArray('password', 'password') in Model.php line 2529
at Model->attributesToArray() in Model.php line 2490
at Model->toArray() in Model.php line 2600
at Model->relationsToArray() in Model.php line 2492
at Model->toArray() in Model.php line 2480
at Model->jsonSerialize() in Collection.php line 1005
at Collection->Illuminate\Support\{closure}(object(Url))
at array_map(object(Closure), array(object(Url), object(Url), object(Url))) in Collection.php line 1013
at Collection->jsonSerialize() in Collection.php line 1024
at Collection->toJson() in Response.php line 68
at Response->morphToJson(object(Collection)) in Response.php line 46
at Response->setContent(object(Collection)) in Response.php line 197
at Response->__construct(object(Collection)) in Router.php line 1030
at Router->prepareResponse(object(Request), object(Collection)) in ControllerDispatcher.php line 95
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in Authenticate.php line 28
at Authenticate->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in ControllerDispatcher.php line 96
at ControllerDispatcher->callWithinStack(object(UsersUrlController), object(Route), object(Request), 'api_filter') in ControllerDispatcher.php line 54
at ControllerDispatcher->dispatch(object(Route), object(Request), '\App\Http\Controllers\Users\UsersUrlController', 'api_filter') in Route.php line 174
at Route->runController(object(Request)) in Route.php line 140
at Route->run(object(Request)) in Router.php line 703
at Router->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in VerifyCsrfToken.php line 64
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 705
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 678
at Router->dispatchToRoute(object(Request)) in Router.php line 654
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 59
I can clearly see that it is trying to decrypt a string "password", of course it will throw an error simply because it is not encrypted, but on my database it is encrypted. Why is it already encrypted before even being decrypted? Is this a possible bug?
Thanks!
Maybe you can try:
public function urls(){
return $this->belongsToMany('\App\Models\SEO\Url', 'user_urls', 'user_id', 'url_id');
}
And call the property like this:
$user=User->with('urls')->where('id',$id)->first();
$user->urls->create_at;

Laravel - Routing error

I am a beginner with Laravel (5.2) and so if this is obvious I apolgise. I have an entry in a Post controller to delete an entry which is passed:
public function getDeletePost( $post_id )
{
$post = Post::where('id', $post_id)->first();
$post->delete();
$message = "successfully deleted";
return redirect()->route('dashboard')->with( ['message'=> $message] );
}
which is called from a function in the routes file:
Route::get('/delete-post/{post_id}',
[ 'uses'=> 'PostController#getDeletePost',
'as' => 'post.delete' ]);
The route is called from a page:
delete
The page is showing the correct URL (http://localhost:8000/post-delete/5) but I am getting the following error and cannot seem to get around it:
Sorry, the page you are looking for could not be found.
1/1 NotFoundHttpException in RouteCollection.php line 161:
in RouteCollection.php line 161
at RouteCollection->match(object(Request)) in Router.php line 823
at Router->findRoute(object(Request)) in Router.php line 691
at Router->dispatchToRoute(object(Request)) in Router.php line 675
at Router->dispatch(object(Request)) in Kernel.php line 246
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 136
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
at Pipeline->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 132
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
at Kernel->handle(object(Request)) in index.php line 54
at require_once('D:\websites\__laravel\socialnetwork\public\index.php') in server.php line 21
Yes a typo! I am suitably humbled!

Seeking help in getting Form Validation working in Laravel 5.2

I'm trying the suggestions for getting validation working on a new Laravel 5.2 install on Bitnami WAMP and having no luck. I have tried both suggestions that are given at Laravel 5.2 $errors not appearing in Blade among other places with the following errors returned from pages that have not even begun using validation.
When I try putting my working route (app/http/routes.php) on Route::group(['middleware' => ['web']], function () {... etc. as follows:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
I get the following error messegaes:
+ RuntimeException in Request.php line 852: Session store not set on request.
+ in Request.php line 852 at Request->session()
+ in ShareErrorsFromSession.php line 42
+ at ShareErrorsFromSession->handle(object(Request), object(Closure))
+ at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
+ at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
+ at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
+ at CheckForMaintenanceMode->handle(object(Request), object(Closure))
+ at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
+ at Pipeline->Illuminate\Pipeline{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
+ at Pipeline->Illuminate\Routing{closure}(object(Request)) at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
+ at Pipeline->then(object(Closure)) in Kernel.php line 132
+ at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
+ at Kernel->handle(object(Request)) in index.php line 54
When I try moving my protected $middlewareGroups web (app/Http/Kernel.php) on protected $middleware = [], as follows:
Route::group(['middleware' => 'web'], function() {
Route::resource('country', 'Region\CountryController');
});
I get the error messages:
+ RuntimeException in EncryptionServiceProvider.php line 31: No supported encrypter found. The cipher and / or key length are invalid.
+ in EncryptionServiceProvider.php line 31
+ at EncryptionServiceProvider->Illuminate\Encryption{closure}(object(Application), array()) in Container.php line 735
+ at Container->build(object(Closure), array()) in Container.php line 633 at Container->make('encrypter', array()) in Application.php line 674
+ at Application->make('Illuminate\Contracts\Encryption\Encrypter') in Container.php line 853
+ at Container->resolveClass(object(ReflectionParameter)) in Container.php line 808
+ at Container->getDependencies(array(object(ReflectionParameter)), array()) in Container.php line 779
+ at Container->build('App\Http\Middleware\EncryptCookies', array()) in Container.php line 633
+ at Container->make('App\Http\Middleware\EncryptCookies', array()) in Application.php line 674
+ at Application->make('App\Http\Middleware\EncryptCookies') in Pipeline.php line 123
+ at Pipeline->Illuminate\Pipeline{closure}(object(Request))
+ at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
+ at Pipeline->Illuminate\Routing{closure}(object(Request))
+ at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
+ at Pipeline->then(object(Closure)) in Router.php line 726
+ at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 699
+ at Router->dispatchToRoute(object(Request)) in Router.php line 675
+ at Router->dispatch(object(Request)) in Kernel.php line 246
+ at Kernel->Illuminate\Foundation\Http{closure}(object(Request))
+ at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
+ at Pipeline->Illuminate\Routing{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
+ at CheckForMaintenanceMode->handle(object(Request), object(Closure))
+ at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
+ at Pipeline->Illuminate\Pipeline{closure}(object(Request))
+ at call_user_func(object(Closure), object(Request)) in Pipeline.php line 32
+ at Pipeline->Illuminate\Routing{closure}(object(Request))
+ at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
+ at Pipeline->then(object(Closure)) in Kernel.php line 132
+ at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99
+ at Kernel->handle(object(Request)) in index.php line 54
These errors come up on a page that is not even asking for validation yet.
When I attempt to get $errors on a blade template that is redirected to after an update in the store method, $errors is not defined either.
Any help is welcome as I have been trying to solve this for several days now in a new Laravel 5.2 installation.
Thank you
(Posting it here as a formal answer)
The second way you mention is more convenient, applying middlewares (or middleware groups, as web is) in your routes definition.
The web group includes middlewares related to session and encrypting. Laravel uses the value of APP_KEY to encrypt all session data, and form inputs and validation errors are stored in the session.
At some point during the session access, Laravel tries to create en Encrypter object, which fails if the application key is not 32 characters long. I just found that reading the source code, but you just need to know that when you do the initial configuration of your application, your .env file should have a 32-long random string as APP_KEY. The Artisan command key:generate does that for you.

Resources