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

Twittler's avatar

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Hi guys, i'm having " Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" problem when i try to send data to database. Any ideas how to fix it?

Index page :

Document

<div class="container">
    <div class="row">
        <div class="col-sm">
            <table>

                <form action="store" method="post">

                    <label for="name">Vardas</label>
                    <input type="text" name="name"> <br>

                    <label for="last-name">Pavarde</label>
                    <input type="text" name="last_name"> <br>

                    <label for="email">email</label>
                    <input type="text" name="email"> <br>

                    <label for="tel.nr">tel.nr</label>
                    <input type="text" name="tel.nr"> <br>

                    <label for="select">Plano pasirinkimas</label><select>
                        @foreach($hostings as $hosting)
                        <option value="{{$hosting['id']}}">{{$hosting['pavadinimas']}}</option>
                        @endforeach
                    </select>
                    <br><input type="submit" value="Pateikti">

                    {{csrf_field()}}

                </form>

            </table>
        </div>
    </div>
</div>

Routes: Route::get('/home', 'HostController@index'); Route::get('/create', 'PostController@index'); Route::post('/store', 'PostController@store');

PostController:

public function index()
{
    return view('index');
}

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
    //
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{

    Posting::create(Request::all());
    return view('index');
}

Model:

class Posting extends Model { protected $primaryKey = 'id'; protected $table = 'client'; public $fillable = ['id','host_id','vardas','pavarde','Tel','email']; }

0 likes
1 reply
BishoyWagih's avatar

please make sure you are sending a correct value for the foreign key , you can make check by typing

dd($request->all())

in your controller store method..

Please or to participate in this conversation.