UUID issue with passport Laravel - laravel

I want to use UUID in Laravel passport instead of the default id in my laravel project.
I changed all the user_id and client_id columns to uuid in the migrations and i add Passport::ignoreMigrations() in the register method in AppServiceProvider.
When i tested in postman by creating a new raw in users table, i get in my response the token but when i use this token in a secured route i always get response status:
401 Unauthorized and in the response body message:Unauthenticated.

things I did to correct this problem:
in AppServiceProvider and register function add:
Passport::ignoreMigrations()
run php artisan vendor:publish --tag=passport-migrations
in CreateOauthAuthCodesTable change to
$table->uuid('id');
$table->primary('id');
$table->uuid('user_id')->index();
so on other passport tables and migrations
in appServiceProvider and boot method add below code:
use Laravel\Passport\Client;
use Ramsey\Uuid\Uuid;
Client::creating(function (Client $client) {
$client->incrementing = false;
$client->id = \Ramsey\Uuid\Uuid::uuid4()->toString();
});
Client::retrieved(function (Client $client) {
$client->incrementing = false;
});
then I migrate my tables with php artisan migrate:fresh (Alert: This command will delete all current tables of database)
the key note is don't forget to add
protected $primaryKey = 'Id'; // in my case I capitalize id to Id
there you are!

You must change the user_id in oauth_access_tokens to uuid type, follow this steps:
Create one migration to alter the table oauth_access_tokens:
php artisan make:migration alter_table_oauth_access_tokens
public function up()
{
Schema::table('oauth_access_tokens', function (Blueprint $table) {
$table->dropColumn('user_id');
});
Schema::table('oauth_access_tokens', function (Blueprint $table) {
$table->uuid('user_id')->index()->nullable();
});
}

php artisan passport:install --uuids

Related

laravel passport:client --personal 'access_token_id' doesn't have a default value

I've installed Laravel Passport (with php artisan passport:install --uuids) and try to generate a PAT. Before this can be done a personal client must be created.
Whenever I run:
php artisan passport:client --personal
a new client will be created to my database, but I get the following error:
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1364 Field 'access_token_id' doesn't have a default value (SQL: insert into `oauth_refresh_tokens` (`client_id`) values (96cf1614-fe2e-42fa-83ba-ac804943c84b))
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:759
755▕ // If an exception occurs when attempting to run a query, we'll format the error
756▕ // message to include the bindings with SQL, which will make this exception a
757▕ // lot more helpful to the developer instead of just the database's errors.
758▕ catch (Exception $e) {
➜ 759▕ throw new QueryException(
760▕ $query, $this->prepareBindings($bindings), $e
761▕ );
762▕ }
763▕ }
+28 vendor frames
29 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
I could fix this by nullableing the blamed field, I'm just wondering if anyone else had the same issue with passport's PAT..
This is the original migration:
public function up()
{
$this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
$table->string('id', 100)->primary();
$table->string('access_token_id', 100)->index();
$table->boolean('revoked');
$table->dateTime('expires_at')->nullable();
});
}
And this update was needed to get it working:
public function up()
{
$this->schema->create('oauth_refresh_tokens', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->uuid('client_id')->nullable()->index();
$table->uuid('access_token_id')->nullable()->index();
$table->boolean('revoked')->nullable();
$table->dateTime('expires_at')->nullable();
});
}
Update
After implementing the above workaround, I run
php artisan passport:client --personal --user_id=11111111-1111-1111-1111-111111111111 --name=PAT
..but the user_id is also not associated in the oauth_clients_table:
id
user_id
name
secret
provider
redirect
personal_access_client
password_client
revoked
created_at
updated_at
96cf9c98-97fa-494d-8f13-01a5856dbe3b
NULL
PAT
$2y$...
NULL
http://localhost
1
0
0
2022-07-18 22:44:56.0
2022-07-18 22:44:56.0
Refresh your database then use this command
php artisan passport:install
I had same problem and this saved me!

Errors in migration when installing the Laravel Voyager package

i have i brand new installation of Laravel 5.5, but when i try to install the Voyager admin panel i have this error :
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `translations` add unique `translati
ons_table_name_column_name_foreign_key_locale_unique`(`table_name`, `column_name`, `foreign_key`, `locale`))
Config
PHP version : 7.0.10
MYSQL version : 5.7.14
CODE UPDATE
I think i have found the concerned code :
Schema::create('translations', function (Blueprint $table) {
$table->increments('id');
$table->string('table_name');
$table->string('column_name');
$table->integer('foreign_key')->unsigned();
$table->string('locale');
$table->text('value');
$table->unique(['table_name', 'column_name', 'foreign_key', 'locale']); // SOURCE OF THE ERROR ?
});
You need to Update the "config/database.php" for 'mysql'.
'engine' => null
To
'engine' => 'InnoDB ROW_FORMAT=DYNAMIC',
also Update the "app/Providers/AppServiceProvider.php"
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Specified key was too long error, Laravel News post:
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
and run these commands in your project folder.
php artisan cache:clear
php artisan config:clear
php artisan voyager:install --with-dummy
The total length of your index is too long.
The column on which the unique index is added shouldn't be such long like VARCHAR columns, because the index will be very bulky and inefficient.
This is a known issue.
If you do not use the muli-language features from Voyager simply uncomment the line in *******************_create_translations_table
// $table->unique(['table_name', 'column_name', 'foreign_key', 'locale']);
or try to update your MySql Database to 7.x

How to fix error Base table or view not found: 1146 Table laravel relationship table?

I am a new of laravel I try to create relationship many to many between table,My problem when I am insert data in to database I got errors
QueryException in Connection.php line 713: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'learn.category_posts' doesn't exist (SQL: insert into category_posts (category_id, posts_id) values (4, ))
can anyone help me pls . and here below is my migrate and code:
2016_08_04_131009_create_table_posts.php
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->text('title');
$table->text('body');
$table->timestamps();
});
}
2016_08_04_131053_create_table_categories.php
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
2016_08_04_131413_create_table_category_posts.php
public function up()
{
Schema::create('category_post', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->integer('post_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
and my model Posts.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Posts extends Model
{
protected $table = 'posts';
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
public function posts()
{
return $this->belongsToMany('App\Posts');
}
}
My PostsController.php
public function create()
{
$categories = Category::all();
return view('create',compact('categories'));
}
public function store(Request $request)
{
$post = new Posts;
$post->title = $request->title;
$post->body = $request->body;
$post->categories()->attach($request->categories_id);
return redirect()->route('posts.index');
}
My View create.blade.php
{!!Form::open(array('route' => 'store', 'method' => 'POST'))!!}
{{Form::text('title')}}<br>
{{Form::textarea('body')}}<br>
<select name="categories_id" multiple>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
<br>
{{Form::submit('submit')}}
{!!Form::close()!!}
It seems Laravel is trying to use category_posts table (because of many-to-many relationship). But you don't have this table, because you've created category_post table. Change name of the table to category_posts.
Laravel tries to guess the name of the table, you have to specify it directly so that it does not give you that error..
Try this:
class NameModel extends Model {
public $table = 'name_exact_of_the_table';
I hope that helps!
Schema::table is to modify an existing table, use Schema::create to create new.
The main problem for causing your table unable to migrate, is that you have running query on your "AppServiceProvider.php" try to check your serviceprovider and disable code for the meantime, and run php artisan migrate
You can add this in Post Model,
public function categories()
{
return $this->belongsToMany('App\Category','category_post','post_id','category_id');
}
category_post indicate the table you want to use.
post_id indicate the column where you want to store the posts id.
category_id indicate the column where you want to store the categories id.
For solving your Base Table or view not found error you can do As #Alexey Mezenin said that change table name category_post to category_posts,
but if you don't want to change the name like in my case i am using inventory table so i don't want to suffix it by s so i will provide table name in model as protected $table = 'Table_name_as_you_want' and then there is no need to change table name:
Change your Model of the module in which you are getting error for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Inventory extends Model
{
protected $table = 'inventory';
protected $fillable = [
'supply', 'order',
];
}
you have to provide table name in model then it will not give error.
The simplest thing to do is, change the default table name assigned for the model. Simply put following code,
protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.
However, if you refer Laravel documentation you'll find the answer. Here what it says,
By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified
Better to you use artisan command to make model and the migration file at the same time, use the following command,
php artisan make:model Test --migration
This will create a model class and a migration class in your Laravel project. Let's say it created following files,
Test.php
2018_06_22_142912_create_tests_table.php
If you look at the code in those two files you'll see,
2018_06_22_142912_create_tests_table.php files' up function,
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
}
Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.
You should change/add in your PostController: (and change PostsController to PostController)
public function create()
{
$categories = Category::all();
return view('create',compact('categories'));
}
public function store(Request $request)
{
$post = new Posts;
$post->title = $request->get('title'); // CHANGE THIS
$post->body = $request->get('body'); // CHANGE THIS
$post->save(); // ADD THIS
$post->categories()->attach($request->get('categories_id')); // CHANGE THIS
return redirect()->route('posts.index'); // PS ON THIS ONE
}
PS: using route() means you have named your route as such
Route::get('example', 'ExampleController#getExample')->name('getExample');
UPDATE
The comments above are also right, change your 'Posts' Model to 'Post'
try checking in the app if you are using the tables before it's created
such as appServiceProvider.php
you might be calling the table without being created it, if you are, comment it then run php artisan migrate.
This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin
If you're facing this error but your issue is different and you're tired of searching for a long time then this might help you.
If you have changed your database and updated .env file and still facing same issue then you should check C:\xampp\htdocs{your-project-name}\bootstrap\cache\config.php file and replace or remove the old database name and other changed items.
Just run the command:
php artisan migrate:refresh --seed
If you are getting the error "SQLSTATE[42S02]: Base table or view not found" and you have no problem in your code, check if you have wrote the first letter of the table in capital letter.
Inspections >> inspections
capital case and small case letters matters on AWS environments.

Is it necessary to write down() for every up() in migration in laravel?

class UpdateSessions extends Migration {
public function up()
{
Schema::table('sessions', function($table){
$table->string('comCode')->nullable()->change();
});
}
public function down()
{
// What should i write here?
}
}
I have already created a sessions table writing a migration to change the column to be nullable.
Now i am confused on what should i write in down?
In the down method of a migration, you undo the changes you made within the up method. This method is called when you rollaback a migration with the artisan migrate:rollback command. In your case it would look something like this:
public function down()
{
// Laravel doesn't have a method to undo ->nullable()
// so you have to do use a raw query in this case
DB::statement('ALTER TABLE sessions MODIFY comCode VARCHAR(255) NOT NULL');
}
So if in your migration up you modified the column named comCode to be nullable, when rolling back the migration you'd need to update that column definition to make it not null, and that's what you do in the down method.
It's not necessary to have anything in the down method in order for the migration to run successfully, however once the migration is ran you won't be able to roll it back unless you have the correct code in the down method.
As of now Dec 2015, at least with Laravel 5 you can just write
Schema::table('sessions', function($table){
$table->string('comCode')->change();
});
Note: this time there is no nullable()

Laravel session table add additional column

I want to add an extra column user_id on session table.
The reason is, some time there are spammer to sign up fake account, once I know that the user is spammer, I want to log the user out by deleting the session record.
Is it possible to achieve this?
This is the session migration schema:
Schema::create('sessions', function($table)
{
$table->string('id')->unique();
$table->text('payload');
$table->integer('last_activity');
$table->integer('user_id')->unsigned(); //// ADD IT!
});
You can add whatever column you like on it, Laravel won't mind.
Or you can create a new migration and make it add a column on that table.
$table->integer('user_id')->unsigned();
You can create a Model for it:
class SessionModel extends Eloquent {
}
And do whatever you need with it:
$session = SessionModel::find(Session::getId());
$session->user_id = 1;
$session->save();
But if you're thinking about adding more info to the payload, which is where Laravel keeps the session data, although I think it's possible, you'll have to dig a bit more in Laravel's code to do that.
Short version of migration
if( Schema::hasTable('sessions') ) {
$table->integer('user_id')->unsigned();
}
Need to check if exist session table. Or create it before:
php artisan session:table
php artisan migrate
https://laravel.com/docs/5.7/session#introduction
This is the session migration schema:
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->unique();
$table->integer('user_id')->nullable();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->text('device')->nullable();
$table->text('payload');
$table->integer('last_activity');
});
To add the information to the payload after adding COLUMN to the TABLE, just change the DatabaseSessionHandler class.
path: vendor/laravel/framework/src/illuminate/Session
Ex:
1º Creates the function
protected function device()
{
$agent = new \Jenssegers\Agent\Agent;
if ($agent->isDesktop()){
$device = 'desktop';
}
return $device;
}
2º add in function addRequestInformation (& $ payload)
protected function addRequestInformation(&$payload)
{
if ($this->container->bound('request')) {
$payload = array_merge($payload, [
'ip_address' => $this->ipAddress(),
'user_agent' => $this->userAgent(),
'device' => $this->device(),
]);
}
return $this;
}
Ready, device added to the table when the user login.

Resources