0





284

Advertisement

I am using Eloquent's firstOrCreate() method to insert my data, or retrieve if it exists.

I need to get the $trip->id. If I echo it in the FlightController then it echo's the correct id, but it doesn't seem to pass it into the UserFlights Model to insert into the user_flights table.

I get this error on the page:

QueryException in Connection.php line 729: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_trips_id' cannot be null (SQL: insert into user_flights (airport_from, airport_to, user_trips_id) values (1, 4, ))

Flow: User select's two airports (flying from and flying to) from the drop-down boxes (<select>) and adds them to their "trip". If they don't have a trip, it creates one, and then adds the two airports to their trip.

Schema

# `user_trips` table
Schema::create('user_trips', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('user_id')->unsigned()->index();
     $table->text('name');
});
# `user_flights ` table
Schema::create('user_flights', function (Blueprint $table) {
     $table->increments('id');
     $table->integer('trip_id')->unsigned();
     $table->integer('airport_from')->unsigned();
     $table->integer('airport_to')->unsigned();
     $table->foreign('trip_id')->references('id')->on('user_trips')->onDelete('cascade');
});

FlightController

<?php

namespace App\Http\Controllers;

use App\UserFlights;
use App\UserTrips;
use Illuminate\Http\Request;

/**
 * Class FlightController
 *
 * @package App\Http\Controllers
 */
class FlightController extends Controller
{
    /**
     * @param Request $request
     * @param UserTrips $user_trips_obj
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request, UserTrips $user_trips_obj)
    {
        // Retrieve the trip by the attributes, or create it if it doesn't exist...
        $trip=$user_trips_obj->addTrip();

        # Returns the ID correctly.
        //echo $trip->id;exit;

        $user_trips_obj->addFlight(
            new UserFlights([
                'airport_from'=>$request->flight_from,
                'airport_to'=>$request->flight_to,
                # Does not pass the `$trip->id` into the UserFlights model.
                'user_trips_id'=>$trip->id
            ])
        );

        return back();
    }
}

UserTrips Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class UserTrips
 *
 */
class UserTrips extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps=FALSE;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable=[
        'name',
        'user_id'
    ];

    /**
     * @param UserFlights $user_flights_obj
     * @return Model
     */
    public function addFlight(UserFlights $user_flights_obj)
    {
        return $this->userflights()->save($user_flights_obj);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function userflights()
    {
        return $this->hasMany('App\UserFlights');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    /**
     * @return mixed
     */
    public function addTrip()
    {
        // Retrieve the trip by the attributes, or create it if it doesn't exist...
        $trip=$this->firstOrCreate([
            'user_id'=>1,
            'name'=>'My Trip'
        ]);

        return $trip;
    }
}

UserFlights Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * Class UserFlights
 *
 */
class UserFlights extends Model
{
    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps=FALSE;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable=[
        'airport_from',
        'airport_to',
        'user_trips_id'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function usertrips()
    {
        return $this->belongsTo('App\UserTrips');
    }
}
Question author Draven | Source

Advertisement


0


Your addFlight() method calls $this->userflights()->save($user_flights_obj);.

When you call save() on the relationship object, it sets the foreign key on the object passed in ($user_flights_obj) to the id of the object that owns the relationship ($this). Then it saves the $user_flights_obj object.

Since your controller calls $user_trips_obj->addFlight(new UserFlights...), the $this reference inside your addFlight() method is referencing the $user_trips_obj instance from your controller. This instance is just an empty shell, with a blank id. Therefore, inside your addFlight() method, when you call save() on the relationship, it is going to set the foreign key on your new UserFlights instance to the id of the instance on which addFlight() was called (blank).

To solve this issue, you just need to call addFlight() on the $trip instance you created in the controller. That is the instance to which you want to relate the new UserFlights instance. Additionally, you don't need to set the foreign key manually; that is the whole reason for calling save() on the relationship.

Answer author Patricus