Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tykus's avatar

Looks like you are perhaps not handling an input correctly, if you are using the code I posted:

{!! Form::checkbox('expectations[]', $expectation->id,true) !!} {!! $expectation->name !!}<br>

then $request->expections is an array and should be handled accordingly.

Can you post your Controller code, or whatever file is identified as causing this error?

1 like
osherdo's avatar

@tykus_ikus thanks. I will describe the situation:

This controller returns the view with 2 variables that one them (expectation) should accept the checkboxes I choose:

http://paste.ofcode.org/XCCiPV8aVUP67DWsEe45ab

This is the relevant code snippet from the view related to the controller above:

http://paste.ofcode.org/Her4TkXgrDtRumjW62uYXb

This is a controller that inserts data to db from the form (UserProfilesController.php):

http://paste.ofcode.org/ep6mneU6wGMx7a9LihLiLa

I should note that the data isn't neccesary for future query but to show the user data based on the choices he made in the form.

tykus's avatar

See comment in the create() method below; you are trying to save an array to a database field - which will not work. You also should have removed the expectations column from the 'profiles' table whenever you created the pivot table, then you can attach()the received expectations array though the relationship

protected function store(Request $request)
{
        $profile = Profile::create([
            'name' => $request['name'],
            'age' => $request['age'],
            'goals' => $request['goals'],
            'activityType' => $request['activityType'],
            // 'expectations' => $request['expectations'] //you are receiving an array and trying to assign it to database field {error}
        ]);
        
        $profile->expectations()->attach($request->expectations);

         return redirect('hub'); 
    }
osherdo's avatar

I get your point now. I also saw that it saves the checboxes and show it in the column like this: 'array' @tykus_ikus I have removed the column from the table. I have done anything according to your suggestions:

class UserProfilesController extends Controller
{
protected function store(Request $request) //That's request object.
{
        $profile = Profile::create([
            'name' => $request['name'],
            'age' => $request['age'],
            'goals' => $request['goals'],
            'activityType' => $request['activityType'],
            'expectations' => $request['expectations']
            
        ]);

    $profile->expectations()->attach($request->expectations);

    return redirect('hub');  
    }

It gives me the error:

ErrorException in helpers.php line 686: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
tykus's avatar

Can you dd($request) and post it here?

In your view, delete these lines:

 &nbsp{!! Form::checkbox('expectations[]','New anerobic routines',true); !!} Find new anerobic routines <br>
 &nbsp{!! Form::checkbox('expectations[]','New aerobic routines',true); !!} Find new aerobic routines <br>
 &nbsp{!! Form::checkbox('expectations[]','Follow',true); !!} Follow other users to get inspired <br>

and fix the foreach loop - you copied my previously suggested code incorrectly; make sure that the checkboxes are called expectations[] and their value is the $expectation->id:

@foreach($expectations as $expectation)
    {!! Form::checkbox('expectations[]', $expectation->id,true) !!} {!! $expectation->name !!}<br>
@endforeach 
osherdo's avatar

But those are my checkboxes. Why to delete them? maybe I should just change the value according to your suggestion. is that right?

 &nbsp{!! Form::checkbox('expectations[]','New anerobic routines',true); !!} Find new anerobic routines <br>
 &nbsp{!! Form::checkbox('expectations[]','New aerobic routines',true); !!} Find new aerobic routines <br>
 &nbsp{!! Form::checkbox('expectations[]','Follow',true); !!} Follow other users to get inspired <br>

I have removed the code for your request. here's dd($request) :

array:5 [▼
  "_token" => "ar73bU14piSHaHtNnpj1AfjB1ywUSrNVuiIiYXCz"
  "gender" => "gender"
  "age" => "22"
  "goals" => "By default,other users can see your goals.dsadsdBy default,other users can see your goals.dsadsdBy d"
  "activityType" => "Aerobics"
]

No expectations name and value here.

tykus's avatar

Delete them! If you did what I suggested previously, you should have an expectations table with the 3 expectations in there. Your checkboxes will be recreated by the the @foreachloop, so that you can correctly to pass the expectation ids into the pivot table. You did create the database tables, didn't you?

Were any of the expectation checkboxes checked by any chance??? Checkbox fields are not included in POST data if they're not checked

osherdo's avatar

Okay I did it as you've asked as I mentioned above.

I get this now:

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

I did created the two tables and 1 model as you've suggested.

Before removed (as you suggested ) I did checked all 3 of them before make a POST request.

talha_malik's avatar

I have a question @tykus_ikus please. It seems @osherdo has a form with three check boxes. Can you please guide me that why he needs to add many to many relationship just to store three values which could be 1 or 0 for selected or not. I do not get the need of creating two more tables and complicating the code. Why I wouldn't just store values of checboxes in my same table when I know it cannot be more than three checkboxes.
I don't mean to negate you but I am little confuse here. I am not very experience programmer too I hope to understand the need here and implement in my future projects too.

Thanks

tykus's avatar

@osherdo Would need to see the full stack trace to know where the Exception was thrown. Did you create the belongsToManyrelationship called expectations in the Profile model?

osherdo's avatar

@tykus_ikus did it well as you've asked before. Expecation.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Expectation extends Model
{
  public function expectations()
{
    return $this->belongsToMany('App\Expectation');
}
}
osherdo's avatar

sorry it must be the late hour.

profile.php:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class profile extends Model
{
        protected $table = 'profiles';

        protected $fillable = ['gender','age','goals','activityType'];
}

I don't have the relationship ready to work. tell me what I need to relate and I will do this.

Tell me generally what's there to do generally.

tykus's avatar

You put the expectations relationship on the Expectation model - this was incorrect, take it out of there and put it into the Profile model

PROFILE MODEL

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class profile extends Model
{
    protected $table = 'profiles';

    protected $fillable = ['gender','age','goals','activityType'];

    public function expectations()
    {
            return $this->belongsToMany('App\Expectation');
    }
}
osherdo's avatar

I will do this first thing in the morning and post here the return. Thanks @tykus_ikus (Must go to sleep now)

Snapey's avatar

It all seems a bit messed up to me, and maybe you have lost or not described the original goal.

You want the user's profile to contain some choices. For the moment, and to avoid confusion, lets call them 'options'

You have three options now, you might have four or two in the future, and rather than hard code the options, you can create an options model and an options table. In this table, you will create the wording of the three options. You will just have an id column and an option column. Your options model does not need any relationships and nothing else relates to options.

When preparing the profile form for display, you will query the options model and get all the options. These can be a simple collection or an array, or does not matter.

In the profile edit view, you will foreach over the options and add a checkbox for each option. The value of the option is the text of the option (not the id). The name for each checkbox should be expectation[]

When the user saves their profile, you need to save any options that they have chosen. Since you will not programmatically use the responses you just need to store them.

Since there can be many options for one profile, you need a table to store them in. Lets call this expectations. So that you can replay to the user what options they chose, you need a link from the expectations to the profile. So your expectations table needs an option column (string) and a profile_id column. The expectations model needs a belongsTo relationship to the profile. The profile model needs a hasMany to the expectations.

When you save the profile you will have an array of expectation entries. Save the profile and then saveMany the array of expectations. This will create one row in the expectations table for each of the selected options, each one having the profile_id set.

If you later need to show the user what they said, you can get their profile ->with('expectations')

If you decide that the user should be allowed to edit their profile, and change the options then you will have to approach things slightly differently. You would have a link from the expectations table to the options table and have the option_id in the expectations table. This then makes the expectations table a pivot. I would still keep the text of the option that they chose in the expectations table in case you change your mind about the wording of each option. You will have the wording they chose at the time, and not the wording as it is currently.

I hope this helps structure your thoughts a bit

1 like
osherdo's avatar

It's now redirecting to where I want and does not show any error. Problem is that expectations aren't saved to the database. @tykus_ikus

that's UserProfileController.php:

http://pastebin.com/ebiAwg3M

that's profile.php (model) http://pastebin.com/Ltum64nc

this is DashboardController.php

http://pastebin.com/GH7s8CeE

and that's the only part in the view that should take care of iterating over checkboxes. no other elements in the view regarding those checkboxes which is interesting.,

http://pastebin.com/8piKVjZK

tykus's avatar

Where are you checking for the expectations? They should be saving to the pivot table (check in mysql) and can be accessed through the relationship:

// Controller
$profile = Profile::findOrFail($id); // a profile that you know you have recently created without errors
// In a view, you can iterate over a Collection of expectations belonging to the `$profile`:
<ul>
@foreach($profile->expectations as $expectation)
    <li>{!! $expectation !!}</li>
@endforeach 
</ul>
osherdo's avatar

@Snapey thanks for the a thoughtful explanation. I think it's the exact solution that @tykus_ikus suggest.

There's nothing in the pivot table (expectation_profile ). Just checked it and re-registered a new user to make sure.

I am confused. please see my code to see if it fits well? should I remove the first foreach in my view?

dashboard.blade.php:

@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)&nbsp I am a: &nbsp{!! Form::radio('gender',null,['class'=>'form-control']) !!} Male
 &nbsp{!! 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)&nbsp My Age is:

{!! Form::number('age', null) !!}


        <p> C)&nbsp What are your fitness goals for the next year?<br></p>
{!! Form::textarea('goals','By default,other users can see your goals.',['class'=>'form-group', 'maxlength'=>100]) !!}</p> <!--default is null -->
<p> D)&nbsp I am better in:</p>
 &nbsp&nbsp&nbsp{!! Form::radio('activityType','Aerobics',null,['class'=>'ActivityType']) !!}  Aerobics
 &nbsp{!! Form::radio('activityType','Anerobic','null',['class'=>'ActivityType']) !!} Anerobic
 &nbsp{!! Form::radio('activityType','both',null,['class'=>'ActivityType']) !!} I am pretty good at both <br><br>
 
<br><br>

@foreach($expectations as $expectation)
    {!! Form::checkbox('expectations[]', $expectation->id,true) !!} {!! $expectation->name !!}<br>
@endforeach 

<ul>
@foreach($profile->expectations as $expectation)
    <li>{!! $expectation !!}</li>
@endforeach 
</ul>

{!! Form::submit('CreateProfile',['class'=>'form-group']) !!}
</div>
        {!! Form::close() !!}
        
    </body>
@stop

UserProfilesController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Profile; //uses the Profile model.
use App\Http\Controllers\Controller;

class UserProfilesController extends Controller
{
protected function store(Request $request) //That's request object.
{
        $profile = Profile::create([
            'name' => $request['name'],
            'age' => $request['age'],
            'goals' => $request['goals'],
            'activityType' => $request['activityType'],
            'expectations' => $request['expectations']
            
        ]);
    $profile = Profile::findOrFail($id); // a profile that you know you have recently created without errors
   
    $profile->expectations()->attach($request->expectations);

    return redirect('hub');  // this is where you redirect to the hub after you store the User
    }
tykus's avatar

Oh maaan... this is tough work! Are you using git and github at all?

OK, the last code I gave you was for the hub controller and view, not the form.

osherdo's avatar

@tykus_ikus sorry for troubling you. just try to be specific with me on this one please.

I do using git with Bitbucket why? need an invitation?

I did corrected the code and put it in the hub controller and view ,accordingly.

But now it won't show me the dashbaord page and show me this error instead:

ErrorException in c3b8369e5906a262c6e3760a4e5a65e9 line 50: Undefined variable: profile (View: /var/www/L53/resources/views/dashboard.blade.php)

I don't have even profile variable in the view (and also not the controller).

osherdo's avatar

@tykus_ikus please tell me your solution as we are almost there. Will try your solution in the morning.

tykus's avatar

I was asking about your source control so I could fork your repo and send you a pull request.

Did you leave this:

<ul>
@foreach($profile->expectations as $expectation)
    <li>{!! $expectation !!}</li>
@endforeach 
</ul>

in the dashboard??

jlrdw's avatar

Have you watched some of the basic laracast series and learned some basic crud prior to Delving too deeply into Laravel?
Of course I would normally place the redirect right after my insert method in the controller I really don't see any other way that makes any sense.

osherdo's avatar

@tykus_ikus I left this in the dashboard.blade.php:

@foreach($expectations as $expectation)
    {!! Form::checkbox('expectations[]', $expectation->id,true) !!} {!! $expectation->name !!}<br>
@endforeach 

and this in the hub.blade.php:

 <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>

https://bitbucket.org/osherdo/sports-application/ - that's my repository. I have just committed the code to the repo now.

Thanks again for everything.

@jlrdw that's the way it is represented in the code: first I typed the insert method and then redirected.

tykus's avatar

You will need to add me to the repo's users in BitBucket - under Settings > Access Management > Users - my username is tykus.

tykus's avatar

Cool, but you also need to push your up-to-date branches - most recent are from 12 January.

Please or to participate in this conversation.