I'm using ramsey/uuid as primary key for all of my project tables. How can I disable auto-increment and allow roles and permissions primary key to be fillable? I have managed to do it on other tables but I'm stuck with these two.
Create a folder in app called Traits. In there, create a file Uuids.php.
Add the following code to Uuids.php;
<?php
namespace YourNamespace;
use Illuminate\Support\Str;
trait Uuids
{
/**
* Boot function from Laravel
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->incrementing = false;
$model->{$model->getKeyName()} = Str::uuid()->toString();
});
}
}
Then in your migration file, you should have something like:
$table->uuid('id')->primary(); to replace $table->increments('id');
Don't forget to use the Uuids trait like so in your models;
<?php
namespace YourNamespace;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use Uuids;
protected $guarded = [''];
protected $casts = [
'id' => 'string',
];
...
Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column:
composer require doctrine/dbal
Next you create a migration file;
php artisan make:migration change_primary_key_type_in_roles_table --table=roles then in your migration file. You do this, eg.
public function up()
{
Schema::table('roles', function (Blueprint $table) {
$table->uuid('id')->change();
});
}
public function down()
{
Schema::table('roles', function (Blueprint $table) {
$table->increments('id')->change();
});
}
Don't forget to do composer dumpautoload.
Hope this helps.
UPDATE: I wrote a blog post on how to achieve this here
Related
So I have just discovered the package laravel-sluggable and I am trying to setup translatable slugs. I got an error with the route model binding, error 404. So I created a simple migration, simple model and simple route, but the same error occurs. My database supports json.
My migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->json('name');
$table->json('slug');
$table->timestamps();
});
}
My model:
<?php
namespace App\Models;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;
use Spatie\Sluggable\HasTranslatableSlug;
class Post extends Model
{
use HasTranslations, HasTranslatableSlug;
public $translatable = ['name', 'slug'];
/**
* Get the options for generating the slug.
*/
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
}
Artisan tinker shows me that the Post I created has been added and it looks like this:
+"name": "{"nl": "test"}",
+"slug": "{"nl": "test"}",
My locale is indeed nl at the moment but browsing to the following route gives me a 404 error:
use App\Models\Post;
Route::get('posts/{post}', function (Post $post) {
dd($post);
});
My question is, what am I missing here? Regular slugs with this package are working like a charm. Also, the translatable package is working like a charm. It is just the translated slugs I am having an issue with right now.
With a fresh Laravel 9 installation it worked like a charm and thus I have upgraded my Laravel 8 to Laravel 9 and it is working now.
I'm trying to write data to my SQLite database. I think there's an error at my migration file and the foreign keys.
I have tried to change names of the files, making the foreign key nullable and clearing Laravel's caches.
Are you familiar with the error that the error handler shows or could you point me towards a page that could help me understand what I'm doing wrong?
Thank you very much in advance.
Migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSqrTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('sqrs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedInteger('user_id')->nullable();
$table->string('qr_link');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('sqr');
}
}
Model file:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
// sQR stands for Saved QR-Code
class sqr extends Model
{
protected $fillable = [
'qr_link', 'user_id'
];
}
Controller that saves:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\sqr;
class saveController extends Controller
{
public function save(Request $request)
{
$sqr = new sqr;
$sqr->qr_link = $request->qr_link;
$sqr->user_id = 1;
$sqr->save();
return redirect('/');
}
}
front end blade file:
<form method="post" action="/save">
#csrf
<input type="hidden" name="qr_link" value="{{ session('url') }}">
<button class="btn btn-success">Save this QR</button>
</form>
The error I'm getting is as follows:
SQLSTATE[23000]: Integrity constraint violation: 19 FOREIGN KEY constraint failed (SQL: insert into "sqrs" ("qr_link", "user_id", "updated_at", "created_at") values (images/1567444499.svg, 1, 2019-09-02 17:37:23, 2019-09-02 17:37:23))
#dparoli said in a comment of this post:
"Are you sure that you have an User with id = 1 in the database? – dparoli"
This was the answer to my question. Because there was nog user = 1 in the database, it crashed.
i want to access to data in the function of the controller using relationships on Laravel.
I will explain first my code:
I have 3 tables, projects, client and client_project.
At this moment, client_project don't have any relationship, i just add it manually.
Now i want to use relationships on laravel, but it's a bit confusing (for me at least).
I think it's not too much important the code of projects and clients table, just have id like primary key, and some fields more.
My migration of client_project looks like here:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateClientProjectTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('client_project', function(Blueprint $table)
{
$table->increments('id');
$table->integer('client_id');
$table->integer('project_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('client_project');
}
}
Client_Project model looks like here:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Client_Project extends Model
{
protected $fillable = ['client_id','project_id'];
public $table = 'client_project';
public function clients()
{
return $this->hasMany('App\Models\Project');
}
public function projects()
{
return $this->hasOne('App\Models\Client');
}
}
One client can have more than one project, but one project is only created by one client. I think relationships are declared good.
(At first, i think with relationships i don't need to make the client_project table), but i think that's a wrong idea. I want to make it with this table too.
So, now, the problem it's when i try to call on the function controller, i think i can access to data using por example:
App\Models\Project::find(1), like doc of laravel says.
The function is this:
$client = new Client();
$client->name = $request->input("nameClient");
$client->slug = $request->input("slugClient");
$client->priority = $request->input("priorityClient");
$client->save();
$client_project = new Client_Project();
$client_project->client_id = App\Models\Client::max('id');
$client_project->project_id = App\Models\Projects::max('id');
$client_project->save();
The part of the client, is working. I just take the value of some inputs and i create a new one.
The problem is with $client_project. I want to make it dynamic. I create the client and the project, and my code get the last one(the bigger id), and the last one(the bigger id too) of projects.
How can i access them using relationships?
Maybe need edit migration of client_project and put some key in project_id or client_id?
If need more information, please ask it.
Any help will be appreciated!
Here is your ans. You are going good way you created pivot table for client and project so you can attached as many projects to any client. Here is relationship with model.
Client Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
public function projects() {
return $this->belongsToMany(Project::class,'client_project');
}
}
Project model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Projects extends Model
{
public function client() {
return $this->belongsToMany(Client::class,'client_project');
}
}
?>
For Save project id use following way in controller method
$client = new Client();
$client->name = $request->input("nameClient");
$client->slug = $request->input("slugClient");
$client->priority = $request->input("priorityClient");
$client->save();
$project = new Project();
//include fields as per your table
$project->save();
$client->projects()->attach($project->id);
.
I'm very confused, i try to find what's wrong but i don't find it..
My migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateClientProjectTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('client_project', function(Blueprint $table)
{
$table->increments('id');
$table->integer('client_id');
$table->integer('project_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('client_project');
}
}
First of all, i check table is created, and it is.
Then, the route who calls to the controller is this: (is prefixed by admin)
Route::post('projectsclients/postUpload', ['uses' => 'AdminController#storeProjectsClients', 'as' => 'admin.projectsclients.store']);
The functions looks like here:
$client_project = new Client_Project();
$client_project->client_id = DB::table('clients')->orderby('id','DESC')->take(1)->get();
$client_project->project_id = DB::table('projects')->orderby('id','DESC')->take(1)->get();
$client_project->save();
And the error:
Base table or view not found: 1146 Table 'web.client__projects'
doesn't exist
The problem is my table is client_project not client__projects.
Where i have to fix this?
Thanks a lot, any help will be appreciated.
You shouldn't be breaking up class name with _ for one. It should be named ClientProject. Generally if there is a problem with the table you would edit the modal and add a
ClientProject.php
public $table = 'client_project';
You are not following Laravel naming conventions. To solve this particular issue yo can explicitly define tabe name. In class Client_Projects definition add this:
protected $table = 'client_project';
But to learn about naming conventions I suggest reading related section in documents here https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions
So I am trying to create a taggable table which enables multiple models to have tags associated with them and felt that Laravel's Polymorphic relationships would be the way to go.
Unfortunately I can't seem to get them working in the following setup. As I receive the following error when running php artisan migrate:refresh --seed.
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class name must be a valid object or a string","file":"...\\vendor\\laravel\\framework\\src\\
Illuminate\\Database\\Eloquent\\Model.php","line":527}}
I believe the issue is due to the fact that the Taggable model has the same morphTo named as outlined below. Since changing this fixes the issue. Why does this cause a problem?
Taggable model
class Taggable extends Eloquent {
protected $table = 'taggable';
public function taggable()
{
return $this->morphTo();
}
}
Track model
class Track extends Eloquent {
protected $table = 'tracks';
protected $fillable = array('title', 'year', 'image');
protected $guarded = array('id');
public function playlists()
{
return $this->belongsToMany('Playlist');
}
public function tags()
{
return $this->morphMany('Taggable', 'taggable');
}
}
Tag model
class Tag extends Eloquent {
protected $table = 'tags';
protected $fillable = array('title', 'description');
protected $guarded = array('id');
}
Migration
Schema::create('taggable', function(Blueprint $table)
{
$table->increments('id');
$table->integer('taggable_id');
$table->string('taggable_type');
$table->integer('tag_id');
$table->timestamps();
});
DatabaseSeeder Snippit
...
DB::table('taggable')->delete();
$track1 = Track::find(1);
$idm = Tag::find(1);
$track1->tags()->create(array('tag_id' => $idm->id));
...
Any help would be much appreciated on this matter.
Try simplifying your relationships - you appear to be using an intermediate table to allow for tag reuse - which is commendable but is complicating your issue.
Start with the Tag and Track models - add additional complexity after you have the basic polymorphic relationship working.
Also, the issue might be that you are using the same name for your Model as the actual relationship function is named. IE Taggable->taggable() vs Tag->taggable()