Laravel Many To Many Relationships update - laravel-9

I am trying to make Many To Many Relationships with Laravel. but where I'm stuck is, when post is updated, how do I update the pivot table?
posts migration
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('body');
$table->timestamps();
});
languages migration
Schema::create('languages', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug');
$table->timestamps();
});
language_post migration
Schema::create('language_post', function (Blueprint $table) {
$table->id();
$table->foreignId('language_id')->constrained();
$table->foreignId('post_id')->constrained();
$table->timestamps();
$table->boolean('active')->default(false);
});
Language Model
public function posts()
{
return $this->belongsToMany(Post::class)
->withTimestamps();
}
Post Model
public function languages()
{
return $this->belongsToMany(Language::class)
->withTimestamps()
->withPivot('active');
}
PostController
class PostController extends Controller
{
public function index()
{
return Post::with('languages')->get();
}
public function store(Request $request)
{
$post = new Post();
$post->title = $request->title;
$post->body = $request->body;
$post->save();
$post->languages()->attach(explode(',', $request->language));
}
public function show($id)
{
$post = Post::find($id);
$post->languages;
return $post;
}
public function update(Request $request, $id)
{
}
public function destroy($id)
{
$postDelete = Post::find($id);
$postDelete->languages()->detach();
return Post::destroy($id);
}
}

Related

getting following error " 150 "Foreign key constraint is incorrectly formed"" on the console

I've checked several times against other projects and I just cannot see what's wrong.
I attach my code:
Schema::table('datos', function (Blueprint $table) {
$table->bigInteger('sensor_id')->change();
$table->foreign('sensor_id')->references('id')->on('sensores')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('datos', function (Blueprint $table) {
$table->dropForeign(['sensor_id']);
});
}
Your function will be look like :
public function up()
{
Schema::create('datos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('sensor_id')->unsigned();
$table->foreign('sensor_id')->references('id')->on('sensores')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('datos');
}
make sure the sensor_id is unsignedBigInteger and move nullable method before change

PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

I am using laravel 6.2, connection is SQL. I am creating two tables, with 'one to many relationship.' Table 'users', and 'managers', where each user will have one manager, and each manager will have more than one user.
Below is the user table migration:
<?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->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->integer('totalBalance')->default(21);
$table->integer('annualBalance')->default(15);
$table->integer('casualBalance')->default(6);
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('manager_id')->unsigned()->index();
$table->foreign('manager_id')->references('id')->on('managers')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
below is the managers migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManagersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('managers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$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('managers');
}
}
below is user model:
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements JWTSubject
{
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',
];
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
public function manager()
{
return $this->belongsTo('App\Manager');
}
}
below is the manager model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Manager extends Model
{
protected $primaryKey = 'id';
public function users()
{
return $this->hasMany('App\User');
}
}
I am getting the below error:
I have tried a lot of things, I saw from other questions online, including changing the type of id (from BigInteger, and integer, and changing engine in database.php to ''InnoDB', and splitting the user model to two parts (2nd part for adding the foreign key).
One thing I saw online (but didn't figure out how to implement), is to change the order of timestamp, as some other suggested that this error might be related to this.
Any suggestion?
This is happening because the user migration is run before creating the manager's table. so Change the migration with the following content will help you to create the foreign key under the manager table.
// user migration file
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->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->integer('totalBalance')->default(21);
$table->integer('annualBalance')->default(15);
$table->integer('casualBalance')->default(6);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
// managers migration file
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateManagersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('managers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Schema::table('users', function (Blueprint $table) {
$table->bigInteger('manager_id')->unsigned()->index();
$table->foreign('manager_id')->references('id')->on('managers')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('managers');
}
}

How To Get data From Request Login Form Laravel

I have a problem, i need get data request from other field on login form to dashboard.
Login Form
enter image description here
My Login Controller, and i use default auth from laravel
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
public function username(){
return 'username';
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
My AuthentictesUser
<?php
namespace Illuminate\Foundation\Auth;
use Illuminate\Http\Request;
use App\Tahun;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
trait AuthenticatesUsers
{
use RedirectsUsers, ThrottlesLogins;
public function showLoginForm()
{
$tahuns = \DB::table('tahuns')->where('active','<>', '2')
->orderBy('id','desc')->get();
return view('auth.login', compact('tahuns'));
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'tahun' => 'required|string',
]);
}
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'password');
}
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
protected function authenticated(Request $request, $user)
{
//
}
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
public function username()
{
return 'email';
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->invalidate();
return redirect('/');
}
protected function guard()
{
return Auth::guard();
}
}
How if i use data from fill tahun(year) on login form?
And i need send data from login form to my dashboard.
There is no need to replace the trait since you can simply override the trait methods in your LoginController, just like you did with username().
Override public function showLoginForm() and return your custom view.
Override protected function validateLogin(Request $request) to validate your new fields.
Finally, override protected function authenticated(Request $request, $user) and save the tahun data or return a redirect response.

Laravel - SQLSTATE[42S22] - Foreign key

I'm trying to implements a 'has one' relation but this error prevent me to save the token.
Migrations :
class CreatePasswordTokensTable extends Migration
{
public function up()
{
Schema::create('password_tokens', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('token');
});
}
...
}
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('email')->unique();
$table->string('password')->default('');
$table->string('remember_token', 100)->default('');
$table->boolean('active')->default(false);
$table->timestamps();
});
}
...
}
Models :
class User extends Model
{
public function passwordToken()
{
return $this->hasOne('App\Models\PasswordToken');
}
}
class PasswordToken extends Model
{
public function user() {
return $this->belongsTo('App\Models\User');
}
}
Commands -
Strange user_id appear after the save call -
Error :
Illuminate\Database\QueryException with message 'SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'user_id' in 'field list' (SQL:
insert into users (email, id, user_id, updated_at,
created_at) values (email, 1, 1, 2017-04-18 10:05:47, 2017-04-18
10:05:47))'
If you are using Laravel 5.3 Try this :
Schema::create('password_tokens', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInt('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('token');
});
I think you can update your model like this:
class User extends Model
{
public function passwordToken(){
return $this->hasOne('App\Models\PasswordToken','user_id', 'id');
}
}
class PasswordToken extends Model
{
public function user()
{
return $this->belongsTO('App\Models\User', 'user_id', 'id');
}
}
Hope this work for you!
Did you fill $table and $fillable attributes at your models?
Did you try the following?
$user->save();
$token->user_id = $user->id;
$token->save();

Query Exception in Connection.php

this is my migration code..... or schema you can say
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
// $table->string('name');
$table->string('to');
$table->string('from');
// $table->string('email')->unique();
$table->string('mobile')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
the Error is shown up when i run this on laravel :
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('to');
$table->string('from');
$table->string('mobile')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
try to use this code,
Also check setting of database related in env file and database.php