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

mozew's avatar
Level 6

How to get inserted row id in laravel?

Hi, I have a problem. How do I get insert id from schools table?

public function store(Request $request)
{
    if($request->ajax()) {
        $activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = School::id;
        $activity->save();

        return response()->json(['data' => $request->all(), 'id' => $activity->school->id]);
    }
}

Database

public function up()
{
    Schema::create('activities', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('school_id')->unsigned();
        $table->integer('cluster_id')->unsigned();
        $table->integer('group_id')->unsigned();
        $table->timestamps();
        
        $table->foreign('school_id')->references('id')->on('schools');
        $table->foreign('cluster_id')->references('id')->on('clusters');
        $table->foreign('group_id')->references('id')->on('groups');
    });
}

Model

class Activity extends Model
{
    public function school()
    {
        return $this->belongsTo(SchoolsList::class);
    }
}
0 likes
25 replies
Cronix's avatar

The same way you saved it.

$activity->school_id = 1;

So

return response()->json(['data' => $request->all(), 'id' => $activity->school_id]);
Snapey's avatar

you havent inserted a school, you inserted an activity?

mozew's avatar
Level 6

No I want to insert own id. How should I do?

        $activity->school_id = School::id;
Snapey's avatar

What school?

Did you just create the school? Is its ID part of the route? Does the user belong to a school?

How will you know WHICH school to link activity to?

mozew's avatar
Level 6

its ID part of the route.

Snapey's avatar

show your route. If it is in the route then you should pass it to the controller

mozew's avatar
Level 6
Route::resource('activity', 'ActivityController');
Snapey's avatar

so there won't be a school ID in that route?

Perhaps an idea to watch through some of the introductory tutorials.

lostdreamer_nl's avatar

You were asking the wrong question (or so it seems)

To answer your question:


        $activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = School::id;
        $activity->save();

    dd($activity->id);

There you have the inserted row id

But you are trying to get the school_id to return in the response, but you never added a school id ( School::id does nothing but give an error (i hope))

By the looks of it, your form should have a select box with all schools (called school_id) and the school_id should be sent via the POST request.

Once you've done that, you should simply do:

public function store(Request $request)
{
    if($request->ajax()) {
        $activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = $request->school_id;
        $activity->save();

        return response()->json(['data' => $request->all(), 'id' => $activity->school_id]);
    }
}
1 like
mozew's avatar
Level 6

Oh, No, I create a school already, a school is belongs to activity or better to say, a school has many activity. Of course I login before then I created a school form and then I created a activity form. I want to only a school be belongs to activity .

For example when a user login.

{{ auth()->user()->id }}

What code do I put for school id now?

Snapey's avatar

What has user->id got to do with school id?

lostdreamer_nl's avatar

@irankhosravi

You really should read up on web programming and follow more tutorials before going this deep in your own projects.

The only way that the user is being remembered in between requests, is because of a thing we call a session and a cookie on the user's computer to identify that session.

If you have a user creating a School object, and later that user creates an Activity object and you want to link that Activity object to the earlier created School object, you'll need to somehow memorize that school's ID.

The somehow part depends completely on your app, we cannot really help you if we don't know much more.

If the user can only create 1 school, and that is their school from then on, you should probably save that school id in the user table (and get it from there everytime the user creates some activity)

If the user can create schools, and can create activities for any school, the Create new Activity form should have some select box for the school_id (like in my previous answer)

If the school and the activity are being created in the same form, you should already have the data needed in the school object you just created.

If you want help on this question you should at the very least

  • explain how that school is created
  • when does the user create an activity in comparison to creating that school
  • how does a user link to a school (or many schools)
  • show the view + javascript that you are using for all this

But I think you're better off going over a tutorial about building a categorised blog for instance, that should teach you most of what you'd need for this.

1 like
mozew's avatar
Level 6

Is it correct?

    if($request->ajax()) {
        $school = School::find($request->input('school_id'));
        $activity = $school->activities()->get();
        $activity = Activity::find($request->id);
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->save();
        return response()->json();
    }

If this have a problem. Please explain problem to me.

lostdreamer_nl's avatar

what are you doing here:

    // why are you getting all activities for this school?
        $activity = $school->activities()->get();
    // why are you now only getting a single activity, I thought you were trying to create a new activity, not update an existing one?
        $activity = Activity::find($request->id);

Check my earlier answer:

    if($request->ajax()) {
        $activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = $request->school_id;
        $activity->save();
        return response()->json(['data' => $request->all(), 'id' => $activity->school_id]);
    }
mozew's avatar
Level 6

@lostdreamer_nl

I checked your answer. I do not want this I want to get last id to save.

How do I should?

I am waiting for an answer.

Tray2's avatar

There are many ways to do this (whatever it is you are asking for).

Not knowing the imagined work flow here but

  • You have a school
  • You want to add an activity to it

Somehow you choose a school that you want to add your activity to.

<form method="POST" action="/acitvity">
<input type="hidden" name="school_id" value="1">
<!--More fields for your activity -->
</form>

Now the school_id is passed to your $request

And you can do this

$activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = $request->school_id;
        $activity->save();

Or if you need to create the school first then you can.

$school = new School();

$school->save()

$activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = $school->id;
        $activity->save();
Snapey's avatar

Still, noone knows what you are trying to do.

Don't just keep saying 'last id'

What id? What do you mean by last? The last one in the database? The last one that was created? The last one for this school? The last school? the last user? the last activity?

Why not just explain what your application is trying to do.

mozew's avatar
Level 6

Let me explain this.

We created a school table with id = 56.

then We created a activity table with id = 1.

Now How to save school_id=56 in activity table.

Tray2's avatar

Check the first part of my previous reply it explains how to pass the school_id into the request where you create your activity.

mozew's avatar
Level 6
<input type="hidden" name="school_id" value="1">

It is value=1

And I want to 56, 57,58....... school_id.

after save form i get this error.

SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into schools (updated_at, created_at) values (2018-08-06 07:19:24, 2018-08-06 07:19:24))

Tray2's avatar

It's an example just give it the id of the chosen school.

<input type="hidden" name="school_id" value="{{ $school->id }}">

Or you can use javascript to populate that value with an ajax request.

mozew's avatar
Level 6

I get this error

Undefined variable: school (View: C:\xampp\htdocs\project\tvto\resources\views\Admin\submit-information\activity.blade.php) (View: C:\xampp\htdocs\project\tvto\resources\views\Admin\submit-information\activity.blade.php)

mozew's avatar
Level 6

I have this in ActivityController and I use ajax and resource

<?php

namespace App\Http\Controllers\Admin;

use App\Activity;
use App\SchoolsList;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ActivityController extends Controller
{
    public function index()
    {

    }

    public function read_activity($id)
    {
        $activities = Activity::with('group', 'cluster')->get();
        return response()->json($activities);
    }

    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        if($request->ajax()) {
            $school = new SchoolsList();
            $school->save();
            $activity = new Activity();
            $activity->cluster_id = $request->cluster_id;
            $activity->group_id = $request->group_id;
            $activity->school_id = $school->id;
            $activity->save();

            return response()->json(['data_activity' => $request->all(), 'id' => $activity->id]);
        }
    }

    public function show(Activity $activity)
    {
        //
    }

    public function edit(Activity $activity)
    {
        //
    }

    public function update(Request $request, Activity $activity)
    {
        if($request->ajax()) {
            $activity = Activity::find($request->id);
            $activity->cluster_id = $request->cluster_id;
            $activity->group_id = $request->group_id;
            $activity->school_id = SchoolsList::latest()->id->get();
            $activity->save();
            return response()->json();
        }
    }

    public function destroy(Activity $activity)
    {
        $activity->delete();
        return response()->json(['success' => 'The person was deleted']);
    }
}

web.php

$this->resource('activity', 'ActivityController');
Tray2's avatar

Once again and this is the last time.

In one of your views you need to pass the current schools id to your ajax request.

The school id need to be in the view for you to pass it.

Maybe the schools.show view.

In you SchoolsController.

public function show($id)
{
    $school = School::findOrFail($id);
    return view('schools.show', compact('school');
}

In your schools show view.

<form method="post" action="/activities" >
    <input type="hidden" name="school_id" value="{{ $school->id }}">
    <button value="Add activity">
</form>

In your activity controller.

$activity->school_id = $request->school_id;

Please or to participate in this conversation.