so i was trying to build a basic referral system where new registered can input there referral username and the referral count will increase and also the referral table will be populated with the referral id and newly user id
i am not getting or doing it right need help
public function register()
{
$user = User::create([
// 'name' => $this->name,
'username' => $this->username,
'email' => $this->email,
'password' => encrypt($this->password)
]);
if ($user = User::where('username', $this->referral)->first()) {
$user->increment('referrel_count');
$user = Referral::create([
'user_id' => auth()->id,
'referred_by_id' => $user->id,
]);
}
$user->notify(new WelcomeUser($user));
Auth::login($user);
return redirect(route('profile.show', auth()->user()->username));
}
table
public function up()
{
Schema::create('referrals', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');
$table->string('referred_by_id')->references('id')->on('users');
$table->timestamps();
});
}
model user
public function referral()
{
return $this->belongsToMany(Referral::class);
}
referral model
public function users()
{
return $this->belongsToMany(User::class);
}
Related
I have a User and an Organization model, bound together by a many-to-many relationship in a organization_user pivot table.
The User model contains:
public function organizations()
{
return $this->belongsToMany(Organization::class);
}
And likewise the Organization model contains:
public function users()
{
return $this->belongsToMany(User::class);
}
Organizations are a resource that a user can create, view, update, delete, and so forth. Of course, users should only be able to view, update and delete the organizations they're part of. I manage to scope the organizations to the current user in the OrganizationController index method, but I'm not sure how to do the same for the edit, update and delete methods. Such guards are not necessary for the create and store methods, I believe.
The controller looks like this:
class OrganizationController extends Controller
{
public function index(Request $request)
{
$organizations = $request->user()->organizations()->get();
return view('organizations.index', compact('organizations'));
}
public function create()
{
return view('organizations.create');
}
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
]);
$request->user()->organizations()->create([
'name' => $request->name,
]);
return redirect()->route('organizations.index');
}
public function edit(Request $request, Organization $organization)
{
// How to make make sure the user is part of the organization?
return view('organizations.edit', [
'organization' => $organization,
]);
}
public function update(Request $request, Organization $organization)
{
// How to make make sure the user is part of the organization?
$request->validate([
'name' => ['required', 'string', 'max:255'],
]);
$organization->update([
'name' => $request->name,
]);
return redirect()->route('organizations.index');
}
}
how can i store data to database in tables
i have two tables in my migration
I want to save the "firstName" to "usersAppointments" table but, it always trying to save the data to "appointments" table
"I'm Beginner"
MIGRATION
public function up()
{
Schema::create('appointments', function (Blueprint $table) {
$table->id();
$table->string('');
$table->string('');
$table->date('');
$table->timestamps();
});
Schema::create('usersAppointments', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->timestamps();
});
}
CONTROLLER
public function store(Request $request){
$data = $request->validate([
'' => 'required',
'' => 'required',
'' => 'required'
]);
Appointment::create($data);
return redirect('/');
}
public function usersAppointment(Request $request){
$data = $request->validate([
'firstName' => 'required'
]);
Appointment::create($data);
return redirect('/');
MODEL
protected $fillable = [
'', '', '',
'firstName'
];
That's because of trying to insert the data into 'Appointment'.
you must write the code as below :
public function usersAppointment(Request $request){
$data = $request->validate([
'firstName' => 'required'
]);
UsersAppointment::create($data);
return redirect('/');
}
I got this error when try to seed database.
Laravel 7.
BlogPost Model
class BlogPost extends Model
{
protected $fillable = [
'title',
'slug',
'user_id',
'category_id',
'excerpt',
'content_raw',
'content_html',
'is_published',
'published_at',
'updated_at',
'created_at',
];
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
User migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
BlogPost migration
Schema::create('blog_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->boolean('is_published')->default(false)->index();
$table->timestamp('published_at')->nullable();
$table->foreign('category_id')->references('id')->on('blog_categories');
$table->timestamps();
});
User seeder
class UserTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'name' => 'Author',
'email' => 'seriiburduja#mail.ru',
'password' => bcrypt('some1234')
],
[
'name' => 'Admin',
'email' => 'seriiburduja#gmail.com',
'password' => bcrypt('some1234')
]
];
DB::table('users')->insert($users);
}
}
BlogPost Factory
$factory->define(BlogPost::class, function (Faker $faker) {
$title = $faker->sentence(rand(3, 8), true);
$text = $faker->realText(rand(1000, 4000));
$isPublished = rand(1, 5) > 1;
$createdAt = $faker->dateTimeBetween('-6 months', '-1 day');
return [
'category_id' => rand(1, 10),
'user_id' => 1,
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
});
DatabaseSeeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(BlogCategorySeeder::class);
factory(BlogPost::class, 1)->create();
}
}
When i run php artisan migrate:fresh --seed i got this error.
Tables users and blog_categories seeds successfully, but error appear for blog_categories.
I don't understand why.
Field user_id exists in $fillable in BlogPost Model.
If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.
Thansk in advance.
In Blog Post Model
Change user relationship to
public function owner()
{
return $this->belongsTo(User::class);
}
In User Model
Add this relationship
public function blogposts()
{
return $this->hasMany(BlogPost::class);
}
In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder
public function run()
{
$user = User::create([
'name' => "Your name",
'email' => "youremail#gmail.com",
'password' => Hash::make('YourPassword')
]);
$this->call(BlogCategorySeeder::class);
$user->blogposts()->saveMany(BlogPost::factory(1));
}
In BlogPost Factory remove user_id
return [
'category_id' => rand(1, 10),
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
fillable is not required when you are using Seeder to insert data.
If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.
In my Laravel application, after a new registration, it connects automatically to this new account.
I just need to register and stay connected with the actual Auth Account. How can we change this default setting?
Because I'm creating new accounts in the application with the admin user.
Thank you
This is my registerController code:
use RegistersUsers;
protected function redirectTo()
{
if(Auth::user()->is_admin == 1){
return 'persons';
}
return '/persons';
}
public function __construct()
{
$this->middleware('auth');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
In Registeruser.php I changed the function register to
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Note please that I create new users using person.blade.php, and not /register
In your App/Http/Controllers/Auth/RegisterController you need to override the method register from RegistersUsers trait:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
This line: $this->guard()->login($user); is where the user gets logged in. You can either remove it or modify it to suit your needs.
Now if you want to redirect after registration to a certain place depending on type of user you'd need to replace protected $redirectTo to:
protected function redirectTo()
{
//You would need to modify this according to your needs, this is just an example.
if(Auth::user()->hasRole('admin')){
return 'path';
}
if(Auth::user()->hasRole('regular_user')){
return 'path';
}
return 'default_path';
}
On top of your file, add these:
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
I am using multi auth login system. I made register, login and mail system. But i don't know how to make update function. Every member needs to update own profile. My problem is i can't get the related users details. id, name, etc...
In my auth.php customer guards was created:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
]
Also this is the CustomerLoginController:
class CustomerLoginController extends Controller{
public function __construct()
{
$this->middleware('guest:customer')->except('logout', 'userLogout');
}
public function showLoginForm(){
return redirect()->route('homepage');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('homepage'));
}
return redirect('/')->with('error_login', 'Login Fail');
}
public function logout(Request $request) {
Auth::guard('customer')->logout();
return redirect('/');
}
I added the function show($id) and function update(Request $request)
But as i told. Can't get the related user.
My last try is:
$user = Customer::find($id);
this is the right way to doing this i think. But i can't connect them.
ps: i am not using --resources (crud). I must do that manually.