someone please?
Trying to store values to db + redirect
Hi I am trying to redirect from 'Dashboard' to 'hub' after form submit. Then I get this:
MethodNotAllowedHttpException in RouteCollection.php line 219:
I couldn't honestly understand what's wrong with my routes this time. It also doesn't insert data to my db as well. model snippet: http://collabedit.com/vg2yg Please help me? thanks.
routes.php
Route::post('dashboard','UserProfilesController@store');
Route::get('dashboard','DashboardController@retrieve');
Route::get('hub','HubController@hub');
UserProfilesController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserProfilesController extends Controller
{
protected function store()
{
// persist the data (insert to db)
//and then redirect to the hub.
return User::create([
'name' => $data['name'],
'age' => $data['age'],
'goals' => $data['goals'],
'activityType' => $data['goals'],
'expectations' => $data['expectations'];
]);
}
}
}
HubController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class HubController extends Controller
{
public function hub()
{
$user = Auth::user();
if($user)
{
return view('hub')->with(compact('user'));
} else{
return redirect('auth/login');
}
How do you do the redirect? Can you give a snipped of the store and redirect part as you have it? Thanks.
- The Model in the link is called
profilewhereas you are trying to create aUserobject in the UserProfilesController. - In the UserProfilesController@store method, what is the
$datavariable? - You are not doing a
redirectin the store method, so why do expect that it should? - Dunno about the Exception being thrown - what is your form's action?
@tykus_ikus thanks for replying:
- thanks. I will fix that up right away.
- to be honest I have copied $data from another view that already insert data to db. But I assume now I should declare this var value somewhere?
- I have placed a redirect in the second method (hub) in HubController.
- I am making the form action on the hub view.
@catalin.zmole I have posted the code above. Can you see it?
someone please?
@osherdo a little time spent watching the tutorials and reading would benefit you greatly, especially the videos!
For now, you need to:
- Make sure that the form in your Blade view with the form is posting to the correct route:
{!! Form::open(['route'=>'dashboard'] !!} // POST is the default method
...
{!! Form::close() !!}
- routes.php
Route::post('dashboard','UserProfilesController@store'); // this is okay
- UserProfilesController.php
We don't know exactly what models you have, so based on the Collabedit link, I am assuming it is a Profile model, and a profiles table. Notice that I have removed the
returnbefore thecreate()method call:
public function store()
{
Profile::create([
'name' => $data['name'],
'age' => $data['age'],
'goals' => $data['goals'],
'activityType' => $data['goals'],
'expectations' => $data['expectations'];
]);
return redirect()->route('hub'); // this is where you redirect to the hub after you store the User
}
@tykus_ikus thanks.
I am getting this error now.
Route [dashboard] not defined. (View: /var/www/L53/resources/views/dashboard.blade.php)
Maybe I should echo the form instead?
echo Form::open(array('route' => 'route.name'))
My fault:
{!! Form::open(['url'=>'/dashboard'] !!} // POST is the default method
...
{!! Form::close() !!}
it gives me this now (after correcting some other typos):
QueryException in Connection.php line 651: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'age' cannot be null (SQL: insert into `profiles` (`age`, `goals`, `activityType`, `expectations`, `updated_at`, `created_at`) values (, , , , 2016-01-17 23:20:10, 2016-01-17 23:20:10))
I believe it's something in the migration structure?
Read the error again... you are not passing any data into the query. There are a couple of things to step thru to make sure that the
-
Check that you have properly specified the
$fillableproperty on the Profile model. Laravel protects against mass-assignment https://laravel.com/docs/5.2/eloquent#mass-assignment -
In your
store()method, what is$data? I asked you about this before... if you want to grab the form data from the request, then you should be using the Request object which should be type hinted in the method signature:
public function store(Request $request)
{
Profile::create([
'name' => $request->input('name'),
'age' => $request->input('age'),
'goals' => $request->input('goals'),
'activityType' => $request->input('activityType'),
'expectations' => $request->input('expectations');
]);
return redirect('hub'); // this is where you redirect to the hub after you store the User
}
@tykus_ikus thanks.
- I already have that in place.
class profile extends Model
{
protected $table = 'profiles';
protected $fillable = ['gender','age','goals','activityType','expectations'];
}
- what's that line supposed to be?
$name = $request->input('name');
- Then this appears:
QueryException in Connection.php line 651: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'expectations' cannot be null (SQL: insert into `profiles` (`age`, `goals`, `activityType`, `expectations`, `updated_at`, `created_at`) values (19, By default,other users can see your goals.dwaqdwadas asas adsf, activityType, , 2016-01-18 13:11:07, 2016-01-18 13:11:07))
I have tried to make activityType Nullable. still gets the same error.
Sorry about (2) that was a 3am error! Updated now.
You're nearly there...
Why did you change activityType if the error specifically complains about expectations?
Do you have an expectation field in you form? What is the field type? If there is not an expectation field, then you will have to change the database table as you have done for activityTypealready
If you die and dump dd($request->all()) it will tell you what you have in the request, and then design your code and table accordingly.
Changed activityType because it throw an error like that also. I confused - I meant to say that 'expectations' row changed to be used with nullable and without - and still gets the same error. Very sorry.
I have changed the name 'improve' to 'expectations' for the 3 radio (field type) buttons. Thanks for the hint- I start to understand the work method here.
Done this: dd($request->all())
and got this screen:
You see the improve on the last row? that needs to be changed to 'expectations'
I could not find the where that improve is.
that's my view:
@extends('layouts.master')
@section('content')
{!! csrf_field() !!}
<body>
<div class="form-group">
<h1>{{ $user->name }}, Welcome to Click-and-Fit Dashboard! </h1>
<h2><strong>Let's Create your gymnast profile:</strong></h2>
{!! Form::open(['url'=>'/dashboard']) !!}
<p> A)  I am a:  {!! Form::radio('gender',null,['class'=>'form-control']) !!} Male
 {!! Form::radio('gender',null,['class'=>'form-group']) !!} Female
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<br><br> B)  My Age is:
{!! Form::number('age', null) !!}
<p> C)  What are your fitness goals for the next year?<br></p>
{!! Form::textarea('goals','By default,other users can see your goals.',['class'=>'form-control', 'maxlength'=>100]) !!}</p> <!--default is null -->
<p> D)  I am better in:</p>
   {!! Form::radio('activityType',null,['class'=>'form-control']) !!} Aerobics
 {!! Form::radio('activityType',null,['class'=>'form-control']) !!} Anerobic
 {!! Form::radio('activityType',null,['class'=>'form-group']) !!} I am pretty good at both <br><br>
E) What do you expect from this app to help you? <br><br> (You can always change this later) <br><br>
 {!! Form::checkbox('expectations','New anerobic routines'); !!} Find new anerobic routines <br>
 {!! Form::checkbox('expectations','New aerobic routines'); !!} Find new aerobic routines <br>
 {!! Form::checkbox('expectations','Follow'); !!} Follow other users to get inspired <br>
<br><br>
{!! Form::submit('CreateProfile',['class'=>'form-group']) !!}
</div>
{!! Form::close() !!}
</body>
@stop
@tykus_ikus I have also made some progress. I just need to change the value to activityType to an actual value. when trying to do this - it returns an error:
constant' aerobics' is not defined.
I also get:
Route [hub] not defined.
@osherdo - sorry, curse of late night coding again... I keep forgetting that you are not using named routes. I have changed the code above for anyone else who looks in to return redirect('hub')
As for the activityType error, what have you changed? Whenever you have an undefined constant error, you have likely either forgotten to put a $ in front of a vriable name, or to wrap a string in quotes
The form input for those radio buttons do not appear to be correct. The correct format is:
{!! Form::radio(name, value, checked, options) !!}
you have omitted the value:
{!! Form::radio('activityType',null,['class'=>'form-control']) !!}
@tykus_ikus no problem it's all good ! :)
So I have managed to get to the hub and data is inserted to db - finally.
I still get the same error:
Use of undefined constant Aerobics - assumed 'Aerobics'
when trying to write it in the format:
<p> D)  I am better in:</p>
   {!! Form::radio('activityType',Aerobics,null,['class'=>'ActivityType']) !!} Aerobics
 {!! Form::radio('activityType',Anerobic,null,['class'=>'ActivityType']) !!} Anerobic
 {!! Form::radio('activityType',both,null,['class'=>'ActivityType']) !!} I am pretty good at both <br><br>
Applicable for all
   {!! Form::radio('activityType','Aerobics' /* Put it in quotes */,null,['class'=>'ActivityType']) !!}
@premsaurav worked well. Thanks. I wish there were some syntax highlighting for blade engine in Sublime text.
So you happen to know how to insert multiple checkboxes (of the same class) to db? (maybe an if/foreach statement in the query?)
E) What do you expect from this app to help you? <br><br> (You can always change this later) <br><br>
 {!! Form::checkbox('expectations','New anerobic routines',true); !!} Find new anerobic routines <br>
 {!! Form::checkbox('expectations','New aerobic routines',true); !!} Find new aerobic routines <br>
 {!! Form::checkbox('expectations','Follow',true); !!} Follow other users to get inspired <br>
<br><br>
@premsaurav thanks I will have a read on it .
Is it also okay that remember_token at db is NULL?
Is it also okay that remember_token at db is NULL?
Didn't get this part?
@premsaurav sorry.
I have a remember_token row at the query. after I execute the query I see that the value is NULL in the remember_token column in the database.
is it okay to be NULL? is that how it's supposed to be?
There is a Laravel Blade Highlighter package available for ST.
You could store a JSON string for the expectations, but in my opinion, this hints at a many-to-many relationship between the UserProfile and an Expectations resource; you would need the following changes:
- a table called
expectationshavingid(integer) andname(string) column; - a pivot table called
expectation_profilehavingprofile_idandexpectation_id(both unsigned integer) column - an
Expectationmodel - an
expectationsrelationship on theProfilemodel:
public function expectations()
{
return $this->belongsToMany('App\Expectation');
}
- Change the name of the
expectationsform field toexpectations[]and you will get the checkboxes as an array; in addition, thevalueof each checkbox should now be theidof an Expectation in your newexpectationstable. You could build your checkboxes like this:
// in the Controller create method, make an $expectations variable to pass thru to the view with the form
$expectations = Expectation::lists('name', 'id');
// in the view
@foreach($expectations as $expectation)
{!! Form::checkbox('expectations[]', $expectation->id,true) !!} {!! $expectation->name !!}<br>
@endforeach
- When you handle the form to create a profile in
UserProfilesController@store, you canattachan array of expectations to the newly created profile:
$profile = Profile::create(...);
$profile->expectations()->attach($request->expectations);
// redirect('hub');
@osherdo I really don't have much idea of what you are trying to achieve and the kind of relationships you are using, however, as far as remember_token is concerned, yes it can be null.
@premsaurav I need to make sure it would suitable for remembering the user even if he closes the app and comes back again sometime. Thanks :)
@tykus_ikus anyway we could discuss this somewhere else (mail or skype or whatever) ?
I would love to hear why your approach is better ? it looks more complicated than what @premsaurav suggested.
You two guys ( @premsaurav ) and especially @tykus_ikus were extremely helpful. thanks again and again.
@tykus_ikus I have lost you in step 5 :( could not make it.
ErrorException in c3b8369e5906a262c6e3760a4e5a65e9 line 45: Undefined variable: expectations (View: /var/www/L53/resources/views/dashboard.blade.php)
The problem is in the view.
You probably made the $expectations variable in the Controller, but didn't actually pass it to the view. You likely already have in your controller something like:
return view('dashboard', compact('variable1', 'variable2', ... ));
Just add 'expectations' to the variables list in compact().
@tykus_ikus thanks again for replying. after fixes I get this:
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
any idea what's wrong here?
Please or to participate in this conversation.