Member Since 1 Year Ago
2,290 experience to go until the next level!
In case you were wondering, you earn Laracasts experience when you:
Earned once you have completed your first Laracasts lesson.
Earned once you have earned your first 1000 experience points.
Earned when you have been with Laracasts for 1 year.
Earned when you have been with Laracasts for 2 years.
Earned when you have been with Laracasts for 3 years.
Earned when you have been with Laracasts for 4 years.
Earned when you have been with Laracasts for 5 years.
Earned when at least one Laracasts series has been fully completed.
Earned after your first post on the Laracasts forum.
Earned once 100 Laracasts lessons have been completed.
Earned once you receive your first "Best Reply" award on the Laracasts forum.
Earned if you are a paying Laracasts subscriber.
Earned if you have a lifetime subscription to Laracasts.
Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.
Earned once you have achieved 500 forum replies.
Earned once your experience points passes 100,000.
Earned once your experience points hits 10,000.
Earned once 1000 Laracasts lessons have been completed.
Earned once your "Best Reply" award count is 100 or more.
Earned once your experience points passes 1 million.
Earned once your experience points ranks in the top 50 of all Laracasts users.
Earned once your experience points ranks in the top 10 of all Laracasts users.
Replied to Cannot Access Any Pages After Installation On Server
I found the issue by listing the routes. One of my controller name started with a lowercase letter and Laravel could find it...
Replied to Cannot Access Any Pages After Installation On Server
@ajithlal Yes, I would say they are. I have done a dd in the autoload.php file and that was displayed on screen after a refresh. I have also done a dd on $app and that is set as well
If that helps I have my site setup as follow /public_html (set as a symlink pointing to laravel /myapp/public/ folder) /myapp/public/index.php (laravel folder)
I have not edited the .htaccess apart from adding a basic htpasword protection for now
Replied to Cannot Access Any Pages After Installation On Server
@jlrdw The .env seems fine. What else could I look into?
Started a new Conversation Custom Validation Rule Message
Hi,
i have create a custom validation for a form
In the rule created by artisan, I have
public function message()
{
return 'The validation error message.';
}
but it does not show when the validation fails.. Instead I get validation.my_validation_rule which from I can see something to do with the language file. How can I display the text in the message function
Started a new Conversation Cannot Access Any Pages After Installation On Server
Hi
I have installed my application on a remote server and all I am getting is the Laravel 404 page This is not a clean install from scratch. This is was deployed from GIT and is working just fine on my local machine.
There is an exception related to routing
/home/myuser/myapp/vendor/laravel/framework/src/Illuminate/Routing/AbstractRouteCollection.php#43
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
I added a dd() in the web.php file and it is not processed. There is clearly an issue finding the web.php
I then went to the routeServideProvider and displayed the base path of the file
/home/myuser/myapp/routes/web.php
which is correct
Does anyone know what the issue could be?
Replied to Different Sessions From Admins And Users
@jlrdw My admin users will create articles and they may want to review them in the public site I have setup my guards correctly I believe,
Is there a way to access session for each user type? I always use
Session::get('var');
or something alike
Is there a way to access secifically the "admin" session ?
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
]
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'admin_password_resets',
'expire' => 60,
'throttle' => 60,
],
],
Replied to Different Sessions From Admins And Users
@snapey @jlrdw I have tested in separate browsers and it works fine However using the same browser, it clearly seems I am using the same session for both users. Logging out from the admin, logs me out from the public site. Looking a the cookies in the inspector shows the same cookie name for 'admin' and 'public'. I am using laravel UI for both login pages.
Replied to Different Sessions From Admins And Users
I have just had a look in private browsing.
Logged in as user A in the public site Opened a new Tab Logged in as user B in the admin site Session data was shared which is not good.
what's the best solution for this? Should I create an "admin" array in my session containing all data data related to admin? and do the same with for users with a "user" array?
Replied to Different Sessions From Admins And Users
Users and admins are two separate entities/model altogether in my system Users login via mysite.com/login Admins login via mysite.com/admin/login
My problem occurs as follow a user "A" logs in the public site. A "has_access" variable is set to True open a new browser Tab an admin "B" logs in the admin site. The "has_access" variable is already set to True
Why do they share the same session?
@snapey Looking at the config file, sessions are stored using 'file'
Started a new Conversation Different Sessions From Admins And Users
Hi,
I have a public and admin site. Frontend users and admins login using different guards but from what I can see they share the same session. Is there a way to prevent this from happening?
Awarded Best Reply on Many To Many Pivot Table
I managed to find a way to update the pivot table.
my function
public function aUserResadsAnArticle($user = NULL, $articleId){
if ($user === NULL)
{
$user = Auth::guard('web')->user();
}
//if the user has not read the article for that year
if (!$user->articleReadThisYear($articleId, NULL)->exists()){
//creates the pivot record
$user->articles()->attach($articleId, ['school_year' => Auth::guard('web')->user()->school_year]);
} else {
$user->articleReadThisYear($articleId, NULL)->updateExistingPivot(
$articleId, ['nb_read' => DB::raw('nb_read+1')]
);
}
}
and the relationship
public function articleReadThisYear(int $articleId, $yearParam = NULL)
{
$year = ($yearParam === NULL) ? Auth::guard('web')->user()->school_year : $yearParam;
return $this->belongsToMany(\App\Models\ContentLive::class)
->withPivot('school_year', 'nb_read', 'feedback')
->wherePivot('school_year', $year)
->wherePivot('content_live_id', $articleId)
->withTimestamps();
}
Replied to Many To Many Pivot Table
I managed to find a way to update the pivot table.
my function
public function aUserResadsAnArticle($user = NULL, $articleId){
if ($user === NULL)
{
$user = Auth::guard('web')->user();
}
//if the user has not read the article for that year
if (!$user->articleReadThisYear($articleId, NULL)->exists()){
//creates the pivot record
$user->articles()->attach($articleId, ['school_year' => Auth::guard('web')->user()->school_year]);
} else {
$user->articleReadThisYear($articleId, NULL)->updateExistingPivot(
$articleId, ['nb_read' => DB::raw('nb_read+1')]
);
}
}
and the relationship
public function articleReadThisYear(int $articleId, $yearParam = NULL)
{
$year = ($yearParam === NULL) ? Auth::guard('web')->user()->school_year : $yearParam;
return $this->belongsToMany(\App\Models\ContentLive::class)
->withPivot('school_year', 'nb_read', 'feedback')
->wherePivot('school_year', $year)
->wherePivot('content_live_id', $articleId)
->withTimestamps();
}
Started a new Conversation Many To Many Pivot Table
I have a many to many relationship between users and articles (called contentLive). All is working fine, but now I need to add a YEAR parameter in my pivot table and it needs to be part of the primary key.
user model
public function articleReadThisYear()
{
return $this->belongsToMany(\App\Models\ContentLive::class)
->withPivot('nb_read', 'feedback')
->where('school_year', Auth::guard('web')->user()->school_year)
->withTimestamps();
}
article model
/**
* Gets the users who have read the article
*/
public function users()
{
return $this->belongsToMany(\App\Models\User::class);
}
I used to create a pivot record using this code
public function aUserReadsAnArticle($user = NULL, $articleId){
if ($user === NULL)
{
$user = Auth::guard('web')->user();
}
$user->articleReadThisYear()->syncWithoutDetaching([
$articleId => ['nb_read' => DB::raw('nb_read+1')]
]);
}
My migration is
Schema::create('content_live_user', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('content_live_id');
$table->unsignedTinyInteger('school_year');
$table->unsignedInteger('nb_read')->default(1);
$table->dateTime('feedback_date')->nullable();
$table->enum('feedback', ['Y', 'N'])->nullable();
$table->timestamps();
$table->primary(['user_id', 'content_live_id', 'school_year']);
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('content_live_id')->references('id')->on('contents_live');
});
How do I change
$user->articleReadThisYear()->syncWithoutDetaching([
$articleId => ['nb_read' => DB::raw('nb_read+1')]
]);
to include the year?
Replied to Eager Loader A Relation
Thanks for that. I could make use of the "When" conditional clause.
I tried the following and the I lost the role name
$adminName = "Will";
$users = Admin::select('first_name', 'last_name', 'uuid', 'email')
->when($adminName, function ($query, $adminName) {
return $query->where('first_name', $adminName);
})->with('roles:name')->get();
Replied to Eager Loader A Relation
@michaloravec @bugsysha @newbie360
$items = Admin::select('id', 'first_name', 'last_name', 'email')->with('roles:name')->get();
works indeed.
I am building a data table filter. I am building the query in multiple stages based on the user selection.
My first line of code is
$items = Admin::select('first_name', 'last_name', 'uuid', 'email')->with('roles:name');
and then I add to it
if (request()->has('institution'))
{
$items = $items->where('institution', $validatedData['institution'] );
}
At the end of the process, I let yajra/laravel-datatables run the query and fetch the results So I never do the ->get(); and as a result I am not getting the role names
but if I do
$items = Admin::with('roles');
I get the correct results
I have run another test The following does not return role name
$items = Admin::select('first_name', 'last_name', 'uuid', 'email')->with('roles:name');
$items = $items->get();
The following returns role name
$items = Admin::select('id', 'first_name', 'last_name', 'email')->with('roles:name')->get();
What is the difference?
Replied to Eager Loader A Relation
I tried both of the above and that does not work. Did I say I use Spatie Laravel-permission?
Started a new Conversation Eager Loader A Relation
Hi,
I am trying to eager a relationship with some fields
$items = Admin::select('first_name', 'last_name', 'email')->with(['roles' => function($query){
return $query->select(['name']);
}]);
#attributes: array:4 [
"first_name" => "xxxxxxxx"
"last_name" => "yyyyyyyy"
"email" => "[email protected]"
]
#relations: array:1 [
"roles" => Illuminate\Database\Eloquent\Collection {#1650
#items: []
}
]
I am able to select my admin fields but my role fields are not selected.
If I run the code below, I get all my fields but I want to specify the fields I need
$items = Admin::with('roles');
Started a new Conversation Filtering A Collection
Hello,
I am trying to build a datable filter but I am struggling to get the code to work
An Admin can belong to many institutions An institution can have many admins
in my admin model
public function institutions()
{
return $this->belongsToMany('App\Models\Institution');
}
in my institution model
public function admins()
{
return $this->belongsToMany('App\Models\Admin\Admin');
}
Above my Admin datatable I have an institution filter. . I have added the following code but that does not return the right collection of admins
$items = Admin::with(['institutions' => function($query) {
$query->whereInstitutionId('institutions.id', '=', 1);
}])->with('roles')->get();
Any tips?
Replied to Image Validation After Selecting From File Manager
@prasadchinwal5 Hi,
There is no form to upload any file. The upload process and file management is all done via a file manager and that is not part of my issue.
When I select a file from the file manager, the relative URL of the file is automatically entered in a text field. This is the file I am trying to validate somehow. I need to find a way to put that file (from the realtive URL) trough the form validator.
Started a new Conversation Image Validation After Selecting From File Manager
HI,
I am trying to get some image validation working on a field fed by a file manager. Upon selection of the file, I expect the validation to occur but it's just not working properly. The error message appears all the time. I have tried to run some tests using the full path of an image and it is not working.
protected $rules = [
'banner' => 'mimes:jpg,jpeg,png,gif'
];
$this->banner = 'E:\path\to\my\site\public\storage\images\my_image.jpg';
$this->validateOnly('banner');
What am I doing wrong? I am doing this validation using livewire but it should be not be the cause of the issue
Started a new Conversation Add/remove Many Tinymce In Form Using Livewire
Hi
I have built a form allowing me to add as many as Tinymce instances as I need. The form is built using livewire.
The HTML generating the form is as follow
<div id="questions" class="tab-pane">
<div class="row">
<div class="col-lg-6">
@foreach($relatedQuestions as $key => $relatedQuestion)
<div class="form-group" >
<div wire:ignore>
{!! Form::textarea('relatedQuestions['.$key.'][title]', '', array( 'placeholder' => 'Question','class' => 'form-control tiny_question_title', 'wire:model.lazy' => 'relatedQuestions.'.$key.'.title', 'id' => 'relatedQuestions['.$key.'][title]' )) !!}
@error('relatedQuestions.'.$key.'.title')<span class="text-danger error">{{ $message }}</span>@enderror
</div>
<button class="btn btn-danger btn-sm" wire:click.prevent="removeRelatedQuestion({{ $key }});">remove</button>
@endforeach
<button class="btn text-white btn-info btn-sm" wire:click.prevent="addRelatedQuestion();">Add a question</button>
</div>
</div>
</div>
I can add as many TinyMCE to the screen as I want, I can save & load them to the DB.
The issue I have is I cannot remove a question. Every time, I use the "remove" button, it removes the correct element in the PHP but on screen, it always remove the last insert TinyMCE instance.
/**
* Add a question
*/
public function addRelatedQuestion()
{
$this->relatedQuestions[] = ['title' => ''];
//converts the textarea to timymce
$this->dispatchBrowserEvent('componentUpdated');
}
/**
* Remove a question
*/
public function removeRelatedQuestion($id)
{
unset($this->relatedQuestions[$id]);
}
The PHP seems correct but It feels the wire:ignore of livewire is not quite working and prevents the deletion of the tinyMCE editor that should be removed.
Started a new Conversation Add/update Record And Increment In Pivot Table In 1 Line
Hi
I have a many to many relationship between users and articles where I store what articles a user reads and keeping track of how many times the article has been read.
I can insert my record my pivot table using
Auth::guard('web')->user()->articles()->sync($article, [ ]);
and update using
Auth::guard('web')->user()->articles()->updateExistingPivot($article, ['nb_read' => DB::raw('nb_read+1') ]);
it works but I am looking for a one line that does insert or update instead of having to write 2 lines. Is that possible?
Started a new Conversation Spatie Tags
Hi,
I am using the spatie/laravel-tags module to tag users. As well as tagging my users, I also need to score the allocated tags. So a user who is interested in maths will be tagged with the "maths" tag and the tag will be given points based on the user's activity in the system.
I have extended the trait, overridden a few functions and I am now able to save a score against a tag. However I am unable to read the score back using eloquent.
The tables are declared like this
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->json('name');
$table->json('slug');
$table->string('type')->nullable();
$table->integer('order_column')->nullable();
$table->timestamps();
});
Schema::create('taggables', function (Blueprint $table) {
$table->integer('tag_id')->unsigned();
$table->morphs('taggable');
$table->unique(['tag_id', 'taggable_id', 'taggable_type']);
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
});
and I have added the score columns
Schema::table('taggables', function (Blueprint $table) {
$table->unsignedInteger('score')->default(0)->after('taggable_id');
$table->unsignedInteger('total_score')->default(0)->after('score');
});
I get my tags using
$tags = $this->selfAssessment->tagsWithType('subject');
This gives me the tag I need and the morph relation. Why isn't the score property there? How can I add it to my results?
Illuminate\Database\Eloquent\Collection {#1758 ▼
#items: array:22 [▼
1 => Spatie\Tags\Tag {#1861 ▼
+translatable: array:2 [▶]
+guarded: []
#connection: "mysql"
#table: "tags"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 29
"name" => "{"en":"Maths"}"
"slug" => "{"en":"Maths"}"
"type" => "subject"
"text" => ""
"order_column" => 29
"created_at" => "2020-12-15 14:22:55"
"updated_at" => "2020-12-15 14:22:55"
]
#original: array:12 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"pivot" => Illuminate\Database\Eloquent\Relations\MorphPivot {#1770 ▼
#morphType: "taggable_type"
#morphClass: "App\Models\SelfAssessment"
+incrementing: false
#guarded: []
#connection: "mysql"
#table: "taggables"
#primaryKey: "id"
#keyType: "int"
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:3 [▼
"taggable_id" => 1
"tag_id" => 29
"taggable_type" => "App\Models\SelfAssessment"
]
#original: array:3 [▶]
#changes: []
#casts: []
#classCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: false
#hidden: []
#visible: []
#fillable: []
+pivotParent: App\Models\SelfAssessment {#1831 ▶}
#foreignKey: "taggable_id"
#relatedKey: "tag_id"
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
#translationLocale: null
}
Replied to Form Validation: Grouped Radio Buttons
My form display a long list of subject for which a user needs to put a score against.
Each subject has radio buttons against it: "I like it", "I don't mid", .... Each of these statements indicates a score
and a statement MUST be selected against each subject.
To me, the only way I can add a required rule against each subject is to run a query in the validation rule function to collect the list of subject and add the required
rule dynamically.
I don't think the laravel rules can get this validated using the
subjects.* => 'required'
I should add my list of subjects can change over time. It is not a static list
Replied to Form Validation: Grouped Radio Buttons
that's true. I did not quite remember that.
What would be the best thing to do for the validation to work in that case.
Should run a DB query in the validation rule function to collect all my different subjects and set the required
rule dynamically? or is there a better way to do this laravel?
Started a new Conversation Form Validation: Grouped Radio Buttons
Hi,
I have a form with several groups of radio buttons. I have left some HTML out to make it easier to read but the main HMTL is down here
<input type="radio" name="subjects[math]" id="subjects[math]['I like it']" value="I like it">
<input type="radio" name="subjects[math]" id="subjects[math]['I dont mind it']" value="I dont mind it">
<input type="radio" name="subjects[math]" id="subjects[math]['not for me']" value="not for me">
<input type="radio" name="subjects[math]" id="subjects[math]['Not applicable']" value="Not applicable">
<input type="radio" name="subjects[english]" id="subjects[english]['I like it']" value="I like it">
<input type="radio" name="subjects[english]" id="subjects[english]['I dont mind it']" value="I dont mind it">
<input type="radio" name="subjects[english]" id="subjects[english]['not for me']" value="not for me">
<input type="radio" name="subjects[english]" id="subjects[english]['Not applicable']" value="Not applicable">
<input type="radio" name="subjects[music]" id="subjects[music]['I like it']" value="I like it">
<input type="radio" name="subjects[music]" id="subjects[music]['I dont mind it']" value="I dont mind it">
<input type="radio" name="subjects[music]" id="subjects[music]['not for me']" value="not for me">
<input type="radio" name="subjects[music]" id="subjects[music]['Not applicable']" value="Not applicable">
My validation is not working
public function rules()
{
return [
'submit' => 'required',
'subjects.*' => 'required',
];
}
If I select a couple of values, the validation passes and I get
array:2 [▼
"submit" => "Next"
"subjects" => array:2 [▼
"math" => "I like it"
"english" => "I like it"
]
]
Why is the rest of the checkboxes not validated? I tried several other solutions including one where I replaced the subject(math, english,...) with a number but that's not working either.
What am I missing?
Started a new Conversation Seeders - Pass Iteration To Factories
Hi,
Is there a way to pass an seeder iteration to a factory?
I would like some of the DB fields not to be fed by faker so they make more sense to me
Currently I have
Seeder
Client::factory()->times(3)->create();
Client Factory
public function definition()
{
return [ 'name' => $this->faker->company]
}
This works fine, but I would like to have
client 1
client 2
for my client names rather than some random names
Is there a way to have Client Factory
public function definition()
{
return [ 'name' => "client ".$seeder_iteration]
}
Replied to Changing The Timeout
OMG... I can't believe I did that. I read the comments above as well.... Must have been a long day....
Many thanks
Started a new Conversation Changing The Timeout
Hi,
I have slight issue when my user times out and I am trying to reduce the timeout to 10 seconds
I have edited the /config/session.php
'driver' => env('SESSION_DRIVER', 'file'), // current setting
'lifetime' => 10, //updated
I ran a php artisan config:clear
Still the timeout is not happening after 10 seconds.
What am I mssing?
Replied to Making An Article Model Live
I like the idea but I think I need to have the "articles live" model as it allows for more flexibility.
To get back to my question, what do I use to copy the article inside articles_live?
$Article = Article::where('id','1'))->get();
$article_live = new Article_live();
$article_live = ???
Replied to Making An Article Model Live
@< gdb >
okay. Maybe I need to add more details for this question There will be time when my administrators will start writing an article but they may not finish it up in one day, or they may want to have the article visible in the web site only from a certain date. In this cases, I would not want my frontend users to have access to these articles because they are not ready and this is why I have 2 models and 2 tables. "Articles" for pages under construction in the admin "ArticlesLive" for for pages that are finished and can be viewed by frontend users
So first, the admin writes the page up. saves it in the DB as an "Article". Then if the article is finished, they can make it live, and this is where I am not quite sure how to do this. I need to copy the article created inside article_live.
Everything you provided is already setup. i just need some idea of how to duplicate the Article and save it in Article_live
I hope it makes sense....
Started a new Conversation Making An Article Model Live
Hi,
I have an "article" model and I need to make it live so it can be seen in the frontend of my site. To do this, I have created an artliceLive model that extends the "article" model
When triggering the "make live" function, I do not know what the best way is to copy all the data from the "articles" table to the "articles_live" table
Same with the relationships
Any tips?
Awarded Best Reply on How To Architecture Content Templates
I have had a go but it does not seem to work....
Schema::create('contents', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('title', 255)->nullable();
$table->string('slug')->nullable();
//$table->unsignedBigInteger('contentable_id');
//$table->string('contentable_type');
$table->morphs('contentable');
$table->foreignId('client_id')->nullable();
$table->timestamps();
$table->softDeletes();
});
Schema::create('content_articles', function (Blueprint $table) {
$table->id();
$table->text('lead')->nullable();
$table->text('body')->nullable();
$table->timestamps();
});
Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Content extends Model
{
use HasFactory;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'body', 'uuid', 'client_id', 'contentable_type', 'contentable_id'
];
public function contentable()
{
return $this->morphTo();
}
}
and my content article
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Content;
class ContentArticle extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'lead', 'body','
];
public function content()
{
return $this->morphOne(Content::class, 'contentable');
}
}
My test is
Route::get('/test', function() {
$article = Content::find(1);
$a = $article->contentable;
dd($a);
});
and I get : Error Class 'App/Models/ContentArticle' not found
I created a dummy record for contents where contentable_type is App/Models/ContentArticle contentable_id is 1
contentArticle contain 1 record with id = 1
I really have no idea why the relationship is not working ....
Replied to How To Architecture Content Templates
I have had a go but it does not seem to work....
Schema::create('contents', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('title', 255)->nullable();
$table->string('slug')->nullable();
//$table->unsignedBigInteger('contentable_id');
//$table->string('contentable_type');
$table->morphs('contentable');
$table->foreignId('client_id')->nullable();
$table->timestamps();
$table->softDeletes();
});
Schema::create('content_articles', function (Blueprint $table) {
$table->id();
$table->text('lead')->nullable();
$table->text('body')->nullable();
$table->timestamps();
});
Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Content extends Model
{
use HasFactory;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'body', 'uuid', 'client_id', 'contentable_type', 'contentable_id'
];
public function contentable()
{
return $this->morphTo();
}
}
and my content article
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Content;
class ContentArticle extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'lead', 'body','
];
public function content()
{
return $this->morphOne(Content::class, 'contentable');
}
}
My test is
Route::get('/test', function() {
$article = Content::find(1);
$a = $article->contentable;
dd($a);
});
and I get : Error Class 'App/Models/ContentArticle' not found
I created a dummy record for contents where contentable_type is App/Models/ContentArticle contentable_id is 1
contentArticle contain 1 record with id = 1
I really have no idea why the relationship is not working ....
Replied to How To Architecture Content Templates
I don't really this approach as I would have to add columns if I add several other templates which is quite likely. I am looking into one-to-one polymorphism to see if that would work. Just running some tests right now. I will post an update when I know if it works ... or not
Started a new Conversation How To Architecture Content Templates
Hi,
I need some advice on how to manage the content of my site
My articles can be of different type. An piece of content can be an article, a poll, a survey, .... I am trying to find the best way to organise these elements with my classes and db
my users will navigate to the pages using www.domain.com/[slug]
I have added the title in the contents
table so when admins go to the "manage content" page, I only have to read in the 1 table in the database
So far I have created the following migration for contents
Schema::create('contents', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('title', 255)->nullable();
$table->string('slug')->nullable();
$table->string('template_type')->nullable();
$table->timestamps();
$table->softDeletes();
});
What would be the best way to attach the content table to the article or poll template
Schema::create('content_articles', function (Blueprint $table) {
$table->id();
$table->text('lead')->nullable();
$table->text('body')->nullable();
$table->timestamps();
});
Schema::create('content_polls', function (Blueprint $table) {
$table->id();
$table->text('question')->nullable();
$table->text('some_other_field')->nullable();
$table->timestamps();
});
Started a new Conversation Image Editor - Cropping To Focal Point
Hi,
I am looking for a a cropping done in laravel that replicates something I have seen in an Umbraco CMS.
It would probably take a million words to explain what I am looking for so I found this old video which displays what I am after
https://www.youtube.com/watch?v=cVVD60NHMRk Jump to 1.00 minutes in the video
This part is the setup of crop sizes for images
At 2.00 minutes, an image is manipulated for each of the image types setup (Thumbnail, main, header). For each image type, the user is able to select where the crop is going to to be done. Usually, the crops are done programmatically and the final image does not look good because the focal point is incorrect (someone's head is cropped, ...). This solves the problem Here with this tool, the focal point can be reviewed by the end user and changed if needed
Has anyone seen anything similar to this done in laravel??
Started a new Conversation Display Livewire Component In Forms If Error
Hi,
I am wondering if it is possible to have a livewire component (dependant dropdowns) in forms.
I want my form to be submitted with a page refresh. I do not want livewire to manage the form validation/submission. I understand how display the component but I am not sure how to display it if the form returns an error. How do I reselect what the user had selected before submitting?
Started a new Conversation Is It Possible To Add A Variable To Route Automatically?
Hi,
I have following route
Route::prefix('/')->middleware('auth','web')->name('frontend.')->namespace('FrontEnd')->domain('{clientSubdomain}.mydomain.com')->group(function() {
Route::get('login', '[email protected]')->name('login');
....
}
In my views, I have
<form method="POST" action="{{ route('frontend.login', ['clientSubdomain' => session('client.subdomain')]) }}">
Is there a way to automatically add the following clientSubdomain variable to the route function without having to declare it all the time?
['clientSubdomain' => session('client.subdomain')]
I would declare the route as follow without the parameter and only add the parameter if I wanted to overwrite it
<form method="POST" action="{{ route('frontend.login') }}">
Replied to Factory
Yep. That works like a charm.
//creates 2 clients
Client::factory()
->times(2)
//creates 3 institutions
->has(Institution::factory()->count(3)
->hasAttached(Admin::factory()->count(3)->state(function (array $attributes, Institution $institution) {
return ['client_id' => $institution->client_id];
}))
The script was indeed missing a bracket because my factory script is a bit longer and had no issue
Replied to Factory
I get the following error:
Argument 2 passed to Database\Seeders\ClientSeeder::Database\Seeders{closure}() must be an instance of App\Models\Client, instance of App\Models\Institution given
Started a new Conversation Factory
Hi,
I would like to know how I can pass dynamically the client id to the admin factory
Client::factory()
->times(2)
//creates 3 institutions
->has(Institution::factory()->count(3)
//attaches 3 admins in pivot table
->hasAttached(Admin::factory( ['client_id' => 1] )->count(3))
Currently the client_id value is set statically to 1 in the admin factory, but there must be a way to get the value dynamically.... I am really stuck
Started a new Conversation Seeding - Assign Roles
Hi,
I am seeding my database and I am struggling to assign roles to my admins. For example I have
//creates 2 clients
Client::factory()
->times(2)
//creates 3 institutions
->has(Institution::factory()->count(3)
//creates 3 "level 1" admins and attach in pivot table
->hasAttached(Admin::factory()->count(3))
//creates 3 users
->has(User::factory()->count(3))
)
->create();
I need to give a role to the admins. I understand the admin needs be persisted for the role to be applied.
$admin->assignRole('Admin level 1');
I can not really use
/**
* Configure the model factory.
*
* @return $this
*/
public function configure()
{
return $this->afterMaking(function (Admin $admin) {
//
})->afterCreating(function (Admin $admin) {
$admin->assignRole('Admin level 1');
});
}
as I need to create other types of users in other factories.
Any suggestions?
Started a new Conversation Nested Routes And Views
Hi,
I have 2 user types. Super admin and Team admin
To edit a player record my super admin navigate through some datagrids screens and will select a division, a team and then a player. The route will be something like this
/admin/division/{division}/team/{team}/player/{player}
Route::resource('divisions.teams.players', 'DivisionTeamPlayerController', ['except' => ['show']]);
To edit a player record my team admin will select NOT a division, but select a team and then a player. The route will be something like this
/admin/team/{team}/player/{player}
Route::resource('teams.players', 'TeamPlayerController', ['except' => ['show']]);
I have followed the documentation in terms of naming https://laravel.com/docs/8.x/controllers#restful-nested-resources. I will add later some middleware on the team admin route to make sure access is allowed for that team and player
When creating the views, depending on the user type. I am going to have to display the correct route in my form. To create a player the super admin user will go to
admin.divisions.teams.players.create
whereas the admin user will go to
admin.teams.players.create
Is it the right way to go for all this nested screens?
All the creation code is going to be duplicated which is not a good thing. I am thinking of putting it in the player model. Is that acceptable? or a service? Which one would be best?
Awarded Best Reply on Help... Livewire Setup
@kitten I finally got it to work.
I have 2 DIVs in my blade file and I can not have that apparently. there must only be 1 DIV
I changed the scipt to
<div style="text-align: center">
<button wire:click="increment">+</button>
<h1>{{ $count }}</h1>
</div>
and it works fine now
Replied to Help... Livewire Setup
@kitten I finally got it to work.
I have 2 DIVs in my blade file and I can not have that apparently. there must only be 1 DIV
I changed the scipt to
<div style="text-align: center">
<button wire:click="increment">+</button>
<h1>{{ $count }}</h1>
</div>
and it works fine now