Caio Kawasaki Caio Kawasaki - 4 months ago 17
PHP Question

How to store the relation between tables

I created a table in relation to two other tables, however I do not know how to relate them when creating new projects, how could I do that?

I'll create the categories in a separated page in my admin, and when the user create's a new project he will be able to select an array of categories coming from the table.

My question is, how can I store the relation when

POST
the data? I've never done this before.

Project model

class Project extends Model
{
protected $table = 'projects';

protected $fillable = [
'name',
'slug',
'header',
'desc',
'about',
'url',
'status'
];

public function customer()
{
return $this->belongsTo(Customer::class);
}

public function category()
{
return $this->belongsToMany(Category::class);
}

public function categories()
{
return $this->hasMany(Category::class);
}
}


Category model

class Category extends Model
{
protected $table = 'categories';

protected $fillable = [
'name',
'status'
];

public function subCategory()
{
return $this->hasMany(SubCategory::class);
}

public function projects()
{
return $this->belongsToMany(Project::class);
}
}


My actual Post create

public function postCreate(ProjectCreateRequest $request, Customer $customer)
{

//Array
$categories = $request->categories;

$customer->projects()->create([
'name' => $request->name,
'header' => $request->header,
'desc' => $request->desc,
'about' => $request->about,
'url' => $request->url,
]);

//How do I store the relation?

return redirect('admin/clientes/editar/' . $customer->id);
}

Answer

use attach or sync for many to many relationships reference : https://laravel.com/docs/5.1/eloquent-relationships#inserting-related-models

public function postCreate(ProjectCreateRequest $request, Customer $customer)
{
    //Array
    $categories = $request->categories;

    $projects = $customer->projects()->create([
        'name' => $request->name,
        'header' => $request->header,
        'desc' => $request->desc,
        'about' => $request->about,
        'url' => $request->url,
    ]);

    //suppose here the $categories is an array of ids or a single integer variable id of the category that are related
    $projects->categories()->attach($categories);

    return redirect('admin/clientes/editar/' . $customer->id);
}
Comments