Monday, March 20, 2017

Laravel user_id in Many-To-Many relationships

Firstly sorry for my bad English.


I have three simple Models:

User

class User extends Authenticatable
{
    protected $fillable = [
        'first_name', 'last_name'
    ];

    public function tickets()
    {
        return $this->hasMany(Ticket::class);
    }

}

Ticket

class Ticket extends Model
{
    protected $fillable = ['user_id', 'title'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function replies()
    {
        return $this->hasMany(TicketReply::class);
    }
}

TicketReply

class TicketReply extends Model
{

    protected $fillable = ['user_id', 'ticket_id', 'text'];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function ticket()
    {
        return $this->belongsTo(Ticket::class);
    }
}

So, For creating a new Ticket it needs to create a Ticket and a Reply.

I'm using below method in TicketController for creating new Ticket :

public function createNewTicket(Request $request)
{
    $ticket  = $request->user()->tickets()->create($request->all());
    $replies = $ticket->replies()->create($request->all()); // Error occurs in this line
}

But it returns this error :

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "user_id" violates not-null constraint ...

The Question Is :

Why Laravel doesn't recognize the owner of TicketReply ?!

I hope I've explained clear enough.

P.S:

Be aware of $request data is like this :

array:2 [▼
  "title" => "My Ticket Title" // `title` field of Ticket Model
  "text" => "Ticket Text Goes Here" // `text` field of TicketReply Model
]



via Hamed Kamrava

Advertisement