Laravel sync store (many-to-many)

  laravel, many-to-many, store, synchronization, upload

I am not very proficient in programming so I would ask for your help. I want to connect the user and tasks table to in my database and assign tasks to different users. Tasks are uploaded successfully but my user_task table is empty after i upload a task. I would like to use many to many relationship, but there is something wrong with the sync(). Because of this issue i cant display tasks for each different users. Please help me what is the problem?!

Create user_task

Schema::create('user_task', function (Blueprint $table) {

            $table->id();
            $table->foreignId('task_id')->constrained()->onDelete('cascade');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->timestamps();
        
        });

Create users

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('avatar')->default('default.jpg');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

Create tasks

Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('alkalmazott');
            $table->string('projekt')->default('-');
            $table->string('feladat');
            $table->date('hatarido');
            $table->timestamps();
        });

Task model

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppModelsUser;

class Task extends Model
{
    use HasFactory;
    protected $fillable = [
        'alkalmazott', 'projekt' , 'feladat', 'hatarido'
    ];
   
    public function projects(){
        return $this->belongsToMany('AppModelsProject');
    }
    public function users()
    {
    return $this->belongsToMany(User::class, 'user_task');
    }
 
}


User model

<?php

namespace AppModels;

use IlluminateContractsAuthMustVerifyEmail;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use IlluminateSupportFacadesHash;
use LaravelSanctumHasApiTokens;
use AppModelsTask;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var string[]
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    //public function setPasswordAttribute($password) {
      //  $this->attributes['password'] = Hash::make($password);
    //}

    public function jogoks(){
        return $this->belongsToMany('AppModelsJogok');
    }
   
   
    public function tasks()
{
  return $this->belongsToMany(Task::class, 'user_task');
}
        /* Check if the user has a role
        * @param string $role
        * @return bool
        */
    public function hasAnyRole(string $role){
        return null !== $this->jogoks()->where('name', $role)->first();        
    }
    /* Check if the user has any given role
        * @param array $role
        * @return bool
        */
    public function hasAnyRoles(array $role){
        return null !== $this->jogoks()->whereIn('name', $role)->first();        
    }

}



Task controller (here i want to upload tasks)

<?php

namespace AppHttpControllers;

use AppModelsProject;
use AppModelsTask;
use AppModelsUser;
use IlluminateHttpRequest;

class TasksController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */
    public function index()
    {
        $tasks = Task::latest()->paginate(10);
    
        return view('admin.tasks.index',compact('tasks'))
            ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return IlluminateHttpResponse
     */
    public function create()
    {
        return view('admin.tasks.create', ['users' => User::all()], ['projects' => Project::all()]);
        
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
     */
    public function store(Request $request)
    {
        $request->validate([
            'alkalmazott' => 'required',
            'projekt' => 'required',
            'feladat' => 'required',
            'hatarido' => 'required',
            
        ]);
        
        $task = Task::create($request->all());
        $task->users()->sync($request->users);

        return redirect()->route('admin.tasks.index')
                        ->with('success','Feladat sikeresen kiosztva!');
    }

    /**
     * Display the specified resource.
     *
     * @param  AppModelsTask  $Task
     * @return IlluminateHttpResponse
     */
    public function show(Task $Task)
    {
        return view('admin.tasks.show',compact('Task'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  AppModelsTask  $Task
     * @return IlluminateHttpResponse
     */
    public function edit(Task $Task)
    {
        return view('admin.tasks.edit',compact('Task'),['users' => User::all(),'projects' => Project::all()]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  AppModelsTask  $Task
     * @return IlluminateHttpResponse
     */
    public function update(Request $request, Task $Task)
    {
        $request->validate([
            'alkalmazott' => 'required',
            'projekt' => 'required',
            'feladat' => 'required',
            'hatarido' => 'required',
        ]);
   
        $task = Task::create($request->validated());
         $task->users->attach($request->users);
    
        return redirect()->route('admin.tasks.index')
                        ->with('success','Feladat sikeresen frissitve!');
                    
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  AppModelsTask  $Task
     * @return IlluminateHttpResponse
     */
    public function destroy(Task $Task)
    {
        $Task->delete();
    
        return redirect()->route('admin.tasks.index')
                        ->with('success','Feladat sikeresen törölve!');
    }
}


And my form where i upload tasks

@extends('templates.main')

@section('content')

  
        <h1 class="float-left">Feladat Kiosztása</h1>
        <div class="row">
            <div class="col-lg-12 margin-tb">
              
                <div class="pull-right">
                    <a class="btn btn-sm btn-primary float-right" href=" {{ route('admin.tasks.index') }}" role="button">Vissza</a>
                </div>
            </div>
        </div>
        <br><br><br><br>

        @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
        <form action="{{ route('admin.tasks.store') }}" method="POST">
            @csrf
            <div class="form-group row">
              <label for="select" class="col-4 col-form-label">Alkalmazott</label> 
              <div class="col-8">
                <select id="alkalmazott" for="exampleFormControlSelect1" name="alkalmazott" required="required" class="custom-select">
                    @foreach($users as $user)
                    <option>{{ $user->name }}</option>
                    @endforeach
                  </select>
              </div>
            </div>
            <div class="form-group row">
                <label for="select" class="col-4 col-form-label">Projekt</label> 
                <div class="col-8">
                  <select id="projekt" for="exampleFormControlSelect1" name="projekt" required="required" class="custom-select">
                      @foreach($projects as $project)
                      <option>{{ $project->name }}</option>
                      @endforeach
                    </select>
                </div>
              </div>
            <div class="form-group row">
              <label for="textarea" class="col-4 col-form-label">Feladat</label> 
              <div class="col-8">
                <textarea id="feladat" name="feladat" cols="40" rows="5" class="form-control"></textarea>
              </div>
            </div>
           <div class="form-group row">
            <label for="textarea" class="col-4 col-form-label">Határidő</label> 
            <div class="col-8">
                    <input type="date" class="form-control {{$errors->has('hatarido') ? 'is-invalid' : ''}}" placeholder="Írja be a határidőt" name="hatarido">
                    <div class="invalid-feedback">{{$errors->first('hatarido')}}</div>
                </div>
            </div>

            
            
            <div class="form-group row">
              <div class="offset-4 col-8">
                <button name="submit" type="submit" class="btn btn-primary">Feladat kiosztása</button>
              </div>
            </div>
          </form>

     
@endsection

And after i run my upload form, on the phpmyadmin the task has uploaded done but in the user_task table is empty. Because its not working i cant display tasks for the users. Thank you for your replies!

Source: Laravel

Leave a Reply