Please I need help, I am working on a project in Laravel, I encounter a problem when T tried to use a pivot table in manay-to-many
In my category model
Category.php
, I have the function below
public function users()
{
return $this->belongsToMany(user::class);
}
In my user model
User.php
, I have the function below
public function authors()
{
return $this->belongsToMany(author::class);
}
In web.php
, I have this
Route::post('/onboarding', 'OnboardsController@categoryUser');
In my onboarding view
, I have a form:
<form action="{{ url('/onboarding') }}" method="POST">
@csrf
@foreach($categories as $category)
<div class="radio-item">
<input class="form control" name="category_id" type="checkbox" id="category_id" required>
<label for="name">{{ $category -> title }}</label>
</div>
@endforeach
<div class="form-row">
<div class="form-group col-md-12 text-center">
<button type="submit">Proceed to Authors</button>
</div>
</div>
</form>
In my OnboardsController
I have this
public function categoryUser (Request $request)
{
$user = User::findOrFail(Auth::user()->id);
$user = categories()->attach($request->input('category_id'));
return redirect ( route ('onboarding_author'));
}
This is the returned error:
Call to undefined function App\Http\Controllers\categories()
When I change the code in my controller to
$category = Category::find($request->input('category_id'));
$user = User::where('user_id', Auth::id());
$category->users()->attach($user->id);
This is the returned error:
Call to undefined function App\Http\Controllers\users()
Here is my full OnboardsController.php
code
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Author;
use App\User;
use App\Category;
class OnboardsController extends Controller
{
public function index()
{
//
return view('onboarding')
->with('categories', Category::all());
}
public function author()
{
//
return view('onboarding_author')
->with('authors', Author::all());
}
public function categoryUser (Request $request)
{
dd(request('category_id'));
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect ( route ('onboarding_author'));
}
Please I am new to Laravel and I have been on this for 3 days, I don't know how to solve this. I need help.