Laravel insert data to multiple tables - php

Hi I need to insert data from register form to 2 or 3 tables, users and members. I need when you click on register button to send only user id and password to users.table and the rest informations into members.table
*edit
My model
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'admin', 'predmet',
];
/**
* 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',
];
}
My migration
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('admin');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I need cote that will import the id, predmet and name to members table

First all of your field create nullable() like these
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->nullable();
$table->integer('admin')->nullable();
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken()->nullable();
$table->timestamps();
});
then in the controller
public function store()
{
$user = new User;
$user->password = bcrypt($request->password);
$user->save();
$member = new Member;
$member->name = $request->name;
$member->username = $request->username;
$member->email= $request->email;
$member->save();
return back();
}

Related

Laravel foreign key doesn't output expected result

I'm developing a Laravel 9 web app and there I have two tables (users and feedbacks) which connects using a foreign key named username. One single user can have many feedbacks. As I know if I get details of a a user those data contains the relevant feedbacks too. My issue is that the user data is fetched properly but it comes with all feedbacks and not the feedbacks which connect to that specific user. The Laravel executes a query like this.
select * from `feedback` where `feedback`.`username` = 0 and `feedback`.`username` is not null
As I understand 0 should be replaced by the user's username. What is the issue here?
Feedback Model-
class Feedback extends Model
{
use HasFactory;
//One single user can have many feedbacks.
public function user() {
return $this->belongsTo(User::class);
}
}
User model-
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'username',
'gender',
'email',
'password',
'is_admin',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
'is_admin',
];
protected $primaryKey = 'username';
public function feedbacks() {
return $this->hasMany(Feedback::class, 'username');
}
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
create_users_table migration-
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('userId');
$table->string('name');
$table->string('username')->unique();
$table->string('gender');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('is_admin')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
create_feedback_table migration-
public function up()
{
Schema::create('feedback', function (Blueprint $table) {
$table->increments('feedbackId');
$table->text('feedback');
$table->string('username');
$table->timestamps();
$table->foreign('username')
->references('username')
->on('users')
->onDelete('cascade');
});
}
FeedbackController to get the data,
class FeedbackController extends Controller
{
public function giveFeedback($username)
{
$userData = User::find($username);
dd($userData->feedbacks);
return view('feedback.givefeedback', compact('userData'));
}
}
users table-
feedback table-
This is the output on the blade, As you can see it outputs all the feedback even though I only requested the feedbacks of nerigupex using routes.
Please request if you need more code to resolve this issue, I will update the question accordingly. TIA.
Do like this (Only addressing Dataload issue)
1. Refator the Migration
User Migration
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id'); # change your current primary key to this
.... rest of the code
}
Feedback Migration
Schema::create('feedback', function (Blueprint $table) {
$table->bigIncrements('id'); # change your current primary key to this
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
.... rest of the code
}
2. Refator the Model
//protected $primaryKey = 'username'; --> remove this
public function feedbacks() {
return $this->hasMany(Feedback::class);
}
3. In Feedback Controller
class FeedbackController extends Controller
{
public function giveFeedback($username)
{
$userData = User::with('feedbacks')->where('username', $username)->get();
dd($userData->feedbacks);
return view('feedback.givefeedback', compact('userData'));
}
}

Why am i getting this error when i try to add foreign keys on Invoice table?

I have two tables users and invoices. This is the up function for the users migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('phone')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('comentarii');
$table->rememberToken();
$table->timestamps();
});
}
This is the up function for the invoices migration:
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->refferences('id')->on('users');
$table->integer('InvoiceNumber');
$table->dateTime('date');
$table->string('serviceInvoiced');
$table->timestamps();
});
}
All I am trying to do is to make a one to many relationship as in a user can have multiple invoices.
Here is the User model:
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $guarded = [];
/**
* 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 getInvoices()
{
return $this->hasMany(Invoice::class);
}
}
Here is the Invoice model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
use HasFactory;
protected $guarded=[];
public function getUsers()
{
return $this->belongsTo(User::class);
}
}
What am I doing wrong? I watched multiple tutorials already. Here are the errors that im getting:
The columns need to be of the same type. id() is an alias of bigIncrements(), so
$table->unsignedInteger('user_id');
should be
$table->unsignedBigInteger('user_id');
Also note: it's ->references('id'), not ->refferences('id')
More on Available Column Types
You have two issues:
You have a typo in your migration statement
$this->id() make unsignedBigInteger so user_id should be unsignedBigInteger
Alter you migration lines to this:
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users'); //references not refferences

Login issues - Credentials do not match in Laravel

Hi Everyone!
I'm using Laravel-8 with Laravel UI. I can able to register any user that is not a problem, but when I log out & try to login again with the same user Credential then I got this error message!
Screenshot-1:
Here is my Database User Table:
Migrations : create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->string('avater')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
UserController.php
public function uploadAvater(Request $request){
if($request->hasFile('image')){
$filename = $request->image->getClientOriginalName();
$request->image->storeAs('images', $filename);
User::find(1)->update(['avater' => $filename]);
}
return redirect()->back();
}
Models-> User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function getNameAttribute($name)
{
return ucfirst($name);
}
}
?>
Does anyone have an idea why I can't able to login in? where is the problem? thanks!
Laravel/ui already hashes the password field when registering. So by using an Eloquent Mutator to hash the password field, you are essentially hashing it twice.
You'll have to either remove the mutator (setPasswordAttribute method) or edit the create() method in RegisterController.

Property [firstName] does not exist on this collection instance

My User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstName', 'secondName', 'email', 'city', 'phoneNumber', 'password', 'profilePicture'
];
/**
* 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',
];
public function ratings()
{
return $this->belongsToMany(Ratings::class, 'ratings_has_users', 'users_id', 'ratings_id')->withTimestamps();
}
}
My Ratings Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Ratings extends Model
{
public function user(){
return $this->belongsToMany(User::class, 'ratings_has_users', 'users_id', 'ratings_id')->withTimestamps();
}
}
MIgration to create table 'ratings_has_users'
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRatingsHasUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('ratings_has_users', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('users_id');
$table->unsignedBigInteger('ratings_id');
$table->timestamps();
});
Schema::table('ratings_has_users', function (Blueprint $table) {
$table->foreign('users_id')
->references('id')
->on('users');
});
Schema::table('ratings_has_users', function (Blueprint $table) {
$table->foreign('ratings_id')
->references('id')
->on('ratings');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ratings_has_users');
}
}
Migration to create 'users' table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstName',55);
$table->string('secondName',55);
$table->string('email',55)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('city',55);
$table->text('description')->nullable();
$table->string('phoneNumber',11);
$table->string('profilePicture',255)->default('profile.jpg');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Migration to create 'ratings' table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateRatingsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('ratings', function (Blueprint $table) {
$table->id();
$table->integer('stars');
$table->mediumText('note');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ratings');
}
}
And code in my blade:
#foreach($ratings as $rating)
{{ dd($rating->user->firstName) }}
#endforeach
I don't know why I see this error message: Property [firstName] does not exist on this collection instance. (View: /data/www/twoj-trener/resources/views/trainer_page/reviews.blade.php)
When I change code on this:
#foreach($ratings as $rating)
{{ dd($rating->user) }}
#endforeach
I got this:
Illuminate\Database\Eloquent\Collection {#1291 ▼
#items: []
}
The relation between rating and user should be users() (with an S for plural) since it's a belongToMany one with a pivot table.
If you want ratings to be unique per user, consider changing your migration of ratings table
public function up()
{
Schema::create('ratings', function (Blueprint $table) {
$table->id();
$table->integer('stars');
$table->mediumText('note');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
and change the relation to belongsTo
if your structure is correct as it is, you will need to get the user before accessing its attribute
#foreach($ratings as $rating)
{{ dd($rating->users->first() ?? $rating->users->first()->firstName) }}
#endforeach
Ratings has user(better name users, because belongsToMany) relation method. If belongsToMany relation that relation method(in this case user) will give the Collection (list related records).
You can do something like below
$rating->user->first()->firstName

Laravel belongsTo relationship not working

I have three models that I have created Post and Comment and User. I am trying to create a relationship in between. Comment and Post they both have a field "user_id" that matches the id on the User table. Below are the relationships that I am trying to set:
Comment.php:
<?php
namespace App;
class Comment extends Model
{
//
public function post(){
return $this->belongsTo(Post::class);
}
public function user(){
return $this->belongsTo(User::class);
}
}
Post.php:
<?php
namespace App;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
public function addComment($body, $name, $email){
$this->comments()->create(compact('body','name','email'));
}
public function user(){ // $comment->user->name
return $this->belongsTo(User::class);
}
}
User.php
<?php
namespace App;
use App\Post;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
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',
];
public function post(){
return $this->hasMany(Post::class);
}
}
Now as you can see a Comment belongsTo a user and a post belongsTo a user.
However when I try to create a new post via tinker (with no user created on database or logged in user) I can create a post with no problem;
That tells me that the relationship that a post must have a user and a comment must have a user as well its not working! Any idea how to fix this ?
Migrations:
create_posts_migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('title');
$table->text('body');
$table->string('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
create_comment_migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCommentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id');
$table->integer('user_id');
$table->string('email');
$table->string('name');
$table->string('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('comments');
}
}
Add the foreign key constraints in your migration to check for valid user when creating a post and to check for valid user and post when creating comments. This should solve your issue.
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('title');
$table->text('body');
$table->string('image');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->unsignedInteger('user_id');
$table->string('email');
$table->string('name');
$table->string('body');
$table->timestamps();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Change the onDelete option based on your needs. The cascade will delete the child relationships when a parent is deleted.

Categories