Sociopath Sociopath - 5 months ago 23
PHP Question

How to validate and create on laravel 5.2 on controller?

Hello I'm trying to create a code generator to invite a user from input email, I want to save on the database the user id who send the invite, the code, and the email who is going to recive the invite, but I can't get the id of my auth user doing $request->user('id') (not working) also I know there is other method to do this easier than using DB::table something like
$request->user()->invites()->create... my controller looks like

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;


class invitacionController extends Controller
{


public function __construct()
{
$this->middleware('auth');

}


public function index(Request $request)
{
return view('administrar');
}



public function invitacion(Request $request)
{
$this->validate($request, [
'email' => 'required|email|max:255|unique:invites',
]);

/*$request->user()->invites()->create([
'code' => str_random(40),
]);*/
DB::table('invites')->insert([
['usuId' => $request->user('id'), 'code' => str_random(40), 'email' => $request->input('email')],
]);

return redirect('/administrar');
}
}

Answer

If the relationship is properly configured, the first (commented) method should be working.

As for the second method, I think you are adding extra brackets:

DB::table('invites')->insert([
    'usuId' => $request->user()->id, // <--- 
    'code' => str_random(40),
    'email' =>  $request->input('email')
]);

That hasMany method can take additional parameters. By default it expects the column to be named user_id, but you called it usuId. The documentation gives this example:

return $this->hasMany('App\Comment', 'foreign_key');

So I think you should do

public function invites()
{
    return $this->hasMany(Invite::class, 'usuId');
}