Automaticlly attach to pivot table in Laravel 5 - php

I currently have a Users to Groups Relationship (ManyToMany) with a pivot table group_user. I want the user to be able to create a group but once creating the group, how do I make it, that the creator becomes member of this group?
Currently I have
My Pivot Table (group_user):
Schema::create('group_user', function(Blueprint $table)
{
$table->integer('group_id')->unsigned()->index();
$table->foreign('group_id')->references('id')->on('groups')->onDelete('cascade');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
My Groups table (groups):
Schema::create('groups', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
My Users table (users):
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('name');
$table->string('lastname');
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
My models ofcourse have the following: User.php
public function groups()
{
return $this->belongsToMany('App\Group');
}
Group.php
public function users()
{
return $this->belongsToMany('App\User');
}
What create function should I write in my controller so that when a User creates a Group, that he automaticly becomes member of this group (automaticlly make the pivot relationship)?

This should work, make sure you implement validation, ect.
public function store(Request $request)
{
$group = Group::create([ // <-- if names are unique. if not, then create is fine
'name' => $request->get('name')
]);
auth()->user()->groups()->attach([$group->id]);
return view('your.view');
}
Also make sure to add:
use App\Group;

See attach() and detach().
$user = User::find(1);
$user->groups()->attach(10); // pivot relationship of this user to group of id 1.
OR
$group = Group::find(10);
$user->groups()->save($group);
For many groups of this user:
$user->groups()->sync(array(1, 2, 3));

Related

How to create many-to-many relationship in Laravel

// the ticket migration
Schema::create('tickets', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title');
$table->text('body');
$table->timestamps();
});
// ticket and status
Schema::create('statuses', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('ticket_status', function (Blueprint $table) {
$table->integer('ticket_id')->unsigned();
$table->integer('status_id')->unsigned();
$table->primary(['ticket_id','status_id']);
});
// store method
public function store()
{
$this->validate(request(), [
'title' => 'required',
'body' => 'required |min:5'
]);
auth()
->user()
->tickets()
->create(request(['title','body','group','status','priority']));
return redirect('/');
}
I have migration for my tickets and I have to get status_id and ticket_id.
When I use create method in my controller table status_ticket do not fill with data.
I do not have an error but my table is empty.
Try to use save, not create. Then the model should be attached
Have you used the methods belongsTo() and hasMany() in your new models?
If not, you have to add these and then you can easily save relations.

give every user role for every page on laravel 5.5

im working on a laravel 5.5 project
and they told me to make role for every page
create edit update delete search softdelete
so i have created user table
this is the migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('user_name',40)->unique();
$table->string('user_email',40)->nullable()->unique();
$table->string('user_phone',40)->nullable()->unique();
$table->integer('user_department');
$table->string('password',60);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
}
and i have created model table this is the migration
public function up()
{
Schema::create('models', function (Blueprint $table) {
$table->increments('id');
$table->string('model_name',40)->unique();
$table->timestamps();
$table->softDeletes();
});
}
and i have created modelroles table
public function up()
{
Schema::create('modelroles', function (Blueprint $table) {
$table->increments('id');
$table->integer('model_id');
$table->integer('user_id');
$table->integer('create');
$table->integer('read');
$table->integer('update');
$table->integer('softdelete');
$table->integer('delete');
$table->integer('restore');
$table->integer('search');
$table->timestamps();
});
}
and i have created middlewaer called roleMiddleware
this is the code
use Closure;
class roleMiddleware
{
public function handle($request, Closure $next)
{
return $next($request);
}
}
so how can i connect them together in the middleware
what i want is to give every user role in every page create read update delete ect
mean check the url the request come from
and check the user id
and check the model id
and check the user_id and the model_id inside modelroles
and if he can create edit update delete on the model
i dont want to use packages like this
https://github.com/laravel-enso/RoleManager
or this
https://github.com/Zizaco/entrust
i dont want to connect users with global role
i want to give every user role for every controller

hasMany relationship is null

I'm new to Laravel 5.0.
I'm trying to make a hasmany relationship between my two models, User and Device.
If in tinker I do App\user::first()->device the result is null
I populated the users and devices tables with some dummy data and the single find() work.
I searched on StackOverflow but I could't find out a solution
Here's my users table
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
my devices table
public function up()
{
Schema::create('devices', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->double('lat', 15, 8);
$table->double('lon', 15, 8);
$table->timestamps();
});
}
and my function in the User Model
public function device()
{
return $this->hasMany('App\Device');
}
Thank you all
The code was right, I found out sometimes tinker needs to be rebooted after the changes in the code

Laravel. Update two tables at one POST method

I have this code right there, this code is working fine and data is successfully stored to table "reports". But I also want to update Users table and their field Credits also. How can I do this in this function ? I also have the relationship between these two tables "reports" and "users".
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
$report->save();
return redirect()->back();
}
Users Table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('credits');
$table->enum('role', ['user', 'admin'])->default('user');
$table->rememberToken();
$table->timestamps();
});
Reports table
Schema::create('reports', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('credits');
You just need to add the logic to update the user (assuming you have a relationship method called user):
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
// if the report has a user, update it
if ($report->user) {
$report->user->credits += Input::get('credits');
$report->user->save();
}
$report->save();
return redirect()->back();
}

Laravel Many to Many Relationship Users on Shift

I'm trying to get the users that are on today's shift. I have a many to many relationship between the User and Shift model with a pivot table called user_shifts.
My User model:
/**
* Get the users shifts
*/
public function shift()
{
return $this->belongsToMany('App\Shift', 'user_shifts', 'user_id', 'shift_id');
}
My Shift model
/**
* The shift can have many users
*/
public function users()
{
return $this->belongsToMany('App\User', 'user_shifts', 'shift_id', 'user_id')->withPivot('start_time', 'end_time');;
}
In my controller I thought I could do something like:
$shift = Shift::all()->where('date', date('Y-m-d'));
$users = User::all()->where('shift_id', $shift);
return $users;
But that is returning null. Any help would be appreciated!
If it matters my db schema is:
Schema::create('shifts', function (Blueprint $table) {
$table->increments('id');
$table->date('date');
$table->boolean('weekend');
});
Schema::create('user_shifts', function (Blueprint $table) {
$table->increments('id');
$table->integer('shift_id');
$table->integer('user_id');
$table->time('start_time');
$table->time('end_time');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('fname');
$table->string('lname');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});

Categories