RFFRED

RFFRED

Member Since 1 Year Ago

Experience Points
9,570
Total
Experience

430 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
66
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    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.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 2
9,570 XP
Oct
17
5 days ago
Activity icon

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?

Sep
28
3 weeks ago
Activity icon

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?

Sep
25
3 weeks ago
Activity icon

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

Activity icon

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

Activity icon

Started a new Conversation Help... Livewire Setup

I am having trouble setting up livewire with L8 I followed the https://laravel-livewire.com/docs/2.x/installation guidance Install The Package Include The Assets Publishing The Config File I then built the https://laravel-livewire.com/docs/2.x/quickstart counter So far so good, so good. I can see the counter.

I click the + button and nothing happens. No ajax is run on the console. nothing happens. no errors.

I can see the livewire element in the laravel-debugbar. It is initialised with some data.

The CSS and the JS file are present in my layout.

I have stripped my layout to the bare bones and it is not making any difference

layout.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>{{ config('app.name', '') }}</title>

  <!-- Tell the browser to be responsive to screen width -->
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- CSRF Token -->
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <base href="/admin/">

  <link rel="stylesheet" href="{{mix('/admin/css/app.css')}}">

  @livewireStyles

</head>
<body class="hold-transition sidebar-mini sidebar-collapse">
            
            @yield('content')

@livewireScripts

</body>
</html>

index.blade.php

@extends('admin.layouts.app')

@section('content')
    <livewire:counter>
@endsection

counter.blade.php

<div>
    <h1>Hello World!!</h1>
</div>

<div style="text-align: center">
    <button wire:click="increment">+</button>
    <h1>{{ $count }}</h1>
</div>

counter.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Counter extends Component
{

    public $count = 0;

    public function increment()
    {
       
        $this->count++;
    }

    public function render()
    {
        return view('livewire.counter');
    }
}

The livewire config file has not been edited

Activity icon

Replied to Having Several Repositories Attached A Controller

@martinbean yep. I had seen livewire a couple of weeks ago but did not quite think to use it for datatables. Watched the laracast episode on i suggested by @automica. Read a couple tutorials. It looks really good. Has anyone used https://github.com/rappasoft/laravel-livewire-tables or https://livewire-datatables.com/ ? I am using bootstrap so I would have convert https://livewire-datatables.com/ but it look pretty neat

Activity icon

Replied to Having Several Repositories Attached A Controller

@martinbean Hi,

Sorry for slow reply. Been very busy coding. I was looking at the Eloquent queries in the context of Yajra data tables as I am testing in some of my screens. There are many posts over the internet complaining about the slowness of Eloquent compared to the query builder https://github.com/yajra/laravel-datatables/issues/1872 It is true the slowness might be due to poor indexing but I don't think it is just that and this video just shows it. https://www.youtube.com/watch?v=3TJfR1Ta4GU

We may only talk miliseconds for a few records in this example but it all adds up. I am more concerned about the people who complain it can takes 15 seconds to load their datatable screen.

I know Eloquent is fast and very practical but there are occasions where it seems to avoid it especially if one knows he is going to have a LOT of records to display.

In terms of the repositories, I can't say I have seen any talk about why one should use repositories and one should not. That's a good point. I understand them and maybe aI am bit too eager to bring these concepts to my application to make it look good. I am by myself learning this mountain of stuff and have no one close but the internet to guide me. So I can be a bit misguided at times by tutorials but I am trying. Your comments help me. The first time I saw them was on the laravel guide. https://laravel.com/docs/8.x/container#automatic-injection and that's how I heard of them. I never realised they were an advanced pattern

Sep
24
4 weeks ago
Activity icon

Replied to Admin Models And Relationships

@jlrdw Understood! Thanks

Activity icon

Replied to Admin Models And Relationships

@jlrdw okay. I think I understand what you are saying. Had to read it 10 times though....

In principles, you say create the relationship function but filter users who can access it.

public function client()
    {
        if (\Auth::guard('admin')->user()->hasAnyRole('super admin', 'client admin', 'advisor') )
        {             
            return $this->hasOne(App\Models\Client::class);
        }
    }

and in the migration I suppose I can the client_id foreign key set to ALLOW NULL

That means all my admins will have relationships to other tables but only few of them will make use the relatoinships. Is that right?

Activity icon

Started a new Conversation Admin Models And Relationships

Hi,

i have an admin model which I use to login to my site. I have 6 different types of administrator and their roles/permissions are managed by spatie/permission.

They all run from the same "admin" model and now, I need to give different relationships to my admins towards other models.

For example, my "super admin" does not need any relationship to my "client" model but my "client admin" needs a one-to-one relationship to my "client" model and my "advisor" also needs a one-to-one relationship to my "client" model, plus a one-to-many relationships with my "institution" model

I am thinking creating "client admin", "advisor" models which would extend my "admin" model

I would still be able to login using the "admin" model.

I am not sure how I go from there because If I log in with an "advisor" user and use

Auth::guard('admin')->user()->

it will point to the "admin" model because this is what I use to run the login check using laravel/UI.

What''s the best way to access the function of the extended class?

Sep
22
1 month ago
Activity icon

Replied to Repository And Transactions

@automica Thanks for the support. I am quite new indeed and only have the web to help me out. I have been playing with it for a few months and now I am making my first application. I still have a few things learn but I will get there. My main issue I have is understanding how all the pieces fit together. There are many ways to accomplish something but knowing how to build the best way is the real trick. I need the experience and those Level 50 gurus are life savers... The comments can be a bit harsh sometimes but I can take it. :)

Sep
21
1 month ago
Activity icon

Replied to Having Several Repositories Attached A Controller

@snapey no I haven't heard of that actually... ;( might put the repositories on hold for the time being if that's what you think.... I was just trying to plan ahead a little and setup some ground work. I wanted to have a base model/controller/repository I can kind of duplicate throughout the project and get things going as quick as. I think it will be painful to have to review and refactor all the controllers in a few weeks time though.

Anyway thanks for the advice. I have a big learning curve ahead of me trying to master this laravel.

Activity icon

Started a new Conversation Repository And Transactions

Hi,

I am looking into repositories and something strikes me me. All the github packages I have seen do not include transactions. Is there a particular reason for that?

All the delete function would look like that:

    public function delete($id) {
        return $this->model->destroy($id);
    }

I have been experimenting a little and the way I think of it is more like this

public function delete($id)
   {

        DB::beginTransaction();

        try {
            
            $user = $this->model->find($id);
          
            if (!$user) {
                throw new ModelNotFoundException('User could not be found');
            }
            
            $user->delete();

            DB::commit();
            
            return True;

        } catch (Exception $e) {

            DB::rollBack();

            throw new GeneralException("Your user could not be deleted", 0, $e);
        }
        
        return False;

   }

Should the transaction be declared in the controller? That seems a lot of code. Do I need to create a service and put all the code in the service??

Activity icon

Replied to Having Several Repositories Attached A Controller

@martinbean I am learning laravel, OOP and I have read a few good and bad things about repository/interfaces. Are you suggesting I should not use them at all? or just for the purpose of datagrids?

From what I have seen here https://www.youtube.com/watch?v=3TJfR1Ta4GU , Eloquent can be a bit slow compared to raw queries.

Maybe I won't use raw queries when the queries get very complicated for my datagrids. I will have to see how fast it loads.

Activity icon

Replied to Obfuscating URLs Securely

@martinbean The system I am building is going to be used by multiple companies. They will all share the same admin system but will only be able view users that are related to their own company. So when editing/deleting user, the ID if not encrypted will be exposed which I do not want. I prefer them to see a uuid although it' is horrible to look at.

Looking ar https://hashids.org/, hashids are breakable from what I have read in their own site. they provide information on how to break them, three quarters down the page. I am not a security expert but I know pretty much everything is breakable if hackers put their mind into it. I do not know personally who is going to use my system but if uuids are one of the best thing at the minute, I think I will go with that

Activity icon

Started a new Conversation Having Several Repositories Attached A Controller

Hi,

I have read using Eloquent is not great in terms of performance when used with databgrids.

I currently have an Eloquent repository attached to a controller and I am wondering if it is a good idea to attach another repository that uses DB. Or alternatively, would I put the functions that use DB inside the Eloquent repository?

I guess I could just put in my controller

$data = DB::select('select * from users');

But I would rather use a repo since I have using that

Also, it's not that I am likely to change my storage system. But I quite like the fact my queries are away from my controller

Sep
20
1 month ago
Activity icon

Replied to Obfuscating URLs Securely

@bobbybouwmann Thanks for confirming. I will use Uuid for my slug. They don't look pretty to say the least but at least they are secure.

Activity icon

Started a new Conversation Obfuscating URLs Securely

Hi,

I need to have my URLs to displayed without any ids. 2 things come in mind, First, using Uuids as primary key but having read about it, I can not use that as I will have too many records and the performance of the system could be damaged over time. Initially I will have the 50,000 records, then growing and growing, the system will go in the millions of records over 2 years+. And from what I have read, Uuids start to consume a lot of time, disk space and memory. Second, obfuscating the URL. This seems a better idea and can be done using a hash. I know [https://hashids.org/] , but it is not secure and I would like it to be.

Could I use something in the middle? Using Uuid as my hash? I guess that would be setup as a binary(16) unique index column in my database?

what do you guys think about this?

Sep
17
1 month ago
Activity icon

Replied to How To Style My Notifications

@snapey

I think there is an issue with

->theme('ck')

when it comes to notifications. The theme is not picked up at runtime I am not expert but after reading the Laravel 8 docs I would expect the theme to be picked up

My solution, for now, is to overwrite the theme set in the config file

            return (new MailMessage)
                ->theme('admin_'.config("mail.markdown.theme"))
                ->subject('Password Reset')
                ->markdown('admin.mail.password.reset', ['url' => $url]);

Mail.php

    'markdown' => [
        'theme' => 'ck',

        'paths' => [
            resource_path('views/vendor/mail'),
            resource_path('views/admin/mail'),
        ],
    ],

(https://laracasts.com/discuss/channels/laravel/mailed-notifications-dont-use-mailmarkdowntheme-setting) Could this bug may have been reintroduced in L8??

Sep
16
1 month ago
Activity icon

Replied to How To Style My Notifications

@snapey

It's definitley not working.

placing the css inside resources/views/html/themes/ck.css does not work

I changed my mail.php config file to

    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
            resource_path('views/admin/mail/themes'),
        ],
    ],

I have added my path to the "paths" array variable. I guess Laravel loops through the array elements until it finds a match.

I have tried many configuration and it only works if the CSS file is in resources\views\vendor\mail\html\themes, and the theme has to be set in the config file for it to work.

I ran

php artisan optimize

between every attempts and it only worked when the ck.css file is in resources\views\vendor\mail\html\themes

I created different folders just in case with different ck.css file just in case. None of them got picked up. They were: resources\views\html\themes as suggested by @niush resources\views\themes resources\views\admin\mail\themes

I also changed the config to

'markdown' => [
        'theme' => 'default',

        'paths' => [
        ],
    ],

and that worked. should it though?

Not sure what to try next

Activity icon

Started a new Conversation How To Style My Notifications

Hi,

I am strugling styling my notifications in Laravel 8. My notification keeps appearing with the default CSS formatting.

code in my notification

 return (new MailMessage)
                ->theme('ck')
                ->subject('Password Reset')
                ->markdown('admin.mail.password.reset', ['url' => $url]);

mail.php


    'markdown' => [
        'theme' => 'default',

        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],

My theme file is in resources\views\admin\mail\themes\ck.css

Activity icon

Started a new Conversation What Does This Blade Code Do?

HI,

I am looking at creating my first notification. I have published the laravel-mail components to theme my mails.

php artisan vendor:publish --tag=laravel-mail

Looking through resources\views\vendor\mail\html\layout.blade.php, I can see the following line

{{ $header ?? '' }}

What does it do?

Activity icon

Awarded Best Reply on Laravel/UI - Forgotten Password Issue

Here is the answer.

In ForgotPasswordController, the broker function needs to have the guard passed as a parameter

/**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        //the guard is passed as parameter
        return Password::broker('admins');
    }

For more info, https://medium.com/backenders-club/password-brokers-reset-passwords-on-multiple-tables-in-laravel-73068542925c

Activity icon

Replied to Laravel/UI - Forgotten Password Issue

Here is the answer.

In ForgotPasswordController, the broker function needs to have the guard passed as a parameter

/**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        //the guard is passed as parameter
        return Password::broker('admins');
    }

For more info, https://medium.com/backenders-club/password-brokers-reset-passwords-on-multiple-tables-in-laravel-73068542925c

Sep
14
1 month ago
Activity icon

Started a new Conversation Laravel/UI - Forgotten Password Issue

Hi

I have been working on integrating Laravel/UI with Laravel 8. I am using a custom guard called "admin" and I have added the authentication controllers in app/Http/Controllers/Admin/Auth. I have also customised the views. I have managed to do the register and the login screens. I am however having issues with sending the link for the forgotten password. I keep getting the message "We can't find a user with that email address."

I have done a bit of digging through the laravel classes and the class responsible for retrieving the user is

/**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials) ||
           (count($credentials) === 1 &&
            Str::contains($this->firstCredentialKey($credentials), 'password'))) {
            return;
        }

        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $query = $this->newModelQuery();

        foreach ($credentials as $key => $value) {
            if (Str::contains($key, 'password')) {
                continue;
            }

            if (is_array($value) || $value instanceof Arrayable) {
                $query->whereIn($key, $value);
            } else {
                $query->where($key, $value);
            }
        }

        return $query->first();
    }

It is located in Illuminate\Auth\EloquentUserProvider

The following line keeps returning a "User" Model but I need to get an "Admin" Model

$query = $this->newModelQuery();

See below the ForgotPasswordController I have customised. I use it to display my view. I also apply the "admin" guard

<?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;


    /**
     * Display the form to request a password reset link.
     *
     * @return \Illuminate\View\View
     */
    public function showLinkRequestForm()
    {
        return view('admin.auth.passwords.email');
    }

    /**
     * Get the guard to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }

}

The above class uses the SendsPasswordResetEmails trait whose purpose is to find the user

SendsPasswordResetEmails which callls sendResetLinkEmail(Request $request)

    {
        $this->validateEmail($request);
       
        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $this->credentials($request)
        );

        return $response == Password::RESET_LINK_SENT
                    ? $this->sendResetLinkResponse($request, $response)
                    : $this->sendResetLinkFailedResponse($request, $response);
    }

$this->credentials($request) Keeps returning NULL as it does not find the user in the DB

I am a bit stuck. Not sure what to do next to fix it...

Sep
10
1 month ago
Activity icon

Started a new Conversation Laravel 8 And Laravel/ui

Hi,

I want to know if it is still fine to use laravel/ui for user authentication in laravel 8 as I am not really interested in JET. Or does laravel 8 provide any authentication option without all the JET stuff?

Aug
12
2 months ago
Activity icon

Replied to Pass Variables To @include

OMG... can't believe I did that... I missed out the .blade

Aug
11
2 months ago
Activity icon

Started a new Conversation Pass Variables To @include

Hi,

I want to pass a variable to a template but I keep getting an error I can not fix

@include('mytemplate', ['var1' => '123'])

mytemplate

{{$var1}}

I get the error

[Vue warn]: Property or method "$var1" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)

I am not sure how to ix this as I have not started to use any vue code at all

Jul
28
2 months ago
Activity icon

Started a new Conversation Delegate Tasks To A Service

Hi,

I am trying to refactor some of my code and remove functions I had in a model into some other class. I am not sure if we call that a helper class or a service....

Template model

class Template extends Model
{

    protected $fillable = [
        'name', 'display'
    ];


    public function update_modules_attached($attributes)
    {
	//removes all modules from the pivot table for this template
        $this->remove_all_modules_attached();

	$this->attach_modules();

    	//do lots of extra stuff
        
    }

    public function remove_all_modules_attached()
    {
        $this->template->modules()->detach();
    }

    public function attach_modules()
    {
    	//do lots of extra stuff
    }

    //creates pivot table relationsip
    public function modules(){
        return $this->belongsToMany('RF\RFTemplates\Models\Admin\TemplateModule');
    }
}

Controller

class TemplateController extends Controller
{

    /**
     * Create a new controller instance.
     * 
     * @return void
     */
    public function __construct()
    {
    }


    public function create()
    {

        $template = new Template;

        //selects all the modules available in the system
        $modules = DB::table('modules')->get();

        //initialises the modules attached to the template
        $used_modules = [];

        return view($this->views_path.'templates.create', compact('template', 'modules', 'used_modules'));
    }


    public function store(TemplateStoreRequest $request)
    {

        // Will return only validated data
        $validatedData = $request->validated();
 
        //create record
        $template = Template::create($validatedData);

        //updates the modules attached to the template
        $template->update_modules_attached(['modules_list'=>$request->input('modules-list')]);

        return redirect()->route('admin.templates.index')
                         ->with('success', trans($this->lang_path.'create_templates.success') );

    }

I would like to move the functions not really related to the model such as: "update_modules_attached", attach_modules() from the model to another class. There are a few other functions not listed here making the model class very big and that should really be moved

So I created a new class.

class TemplateManagerService
{

	protected $template;


    /**
     * Create a new instance.
     * 
     * @return void
     */
    public function __construct(Template $template)
    {

    	$this->template = $template;

    }

    public function remove_all_modules_attached()
    {

        $this->template->modules()->detach();

    }

    /**
     * Update the template's modules in the pivot table
     *
     * @param  Array  $attributes
     * @return 
     */
    function update_modules_attached($attributes)
    {

	//removes all modules from the pivot table for this template
        $this->template->remove_all_modules_attached();

     }

I have updated my controller to accept the service


class TemplateController extends Controller
{

    private $templateManagerService;

    /**
     * Create a new controller instance.
     * 
     * @return void
     */
    public function __construct(TemplateManagerService $templateManagerService)
    {

        $this->templateManagerService = $templateManagerService;

    }

    public function create(){
	    //does not change
    }

    public function store(TemplateStoreRequest $request)
    {

        // Will return only validated data
        $validatedData = $request->validated();
 
        //create record
        $template = Template::create($validatedData);

        $this->templateManagerService->remove_all_modules_attached();

        return redirect()->route('admin.templates.index')
                         ->with('success', trans($this->lang_path.'create_templates.success') );

    }

What I do not understand is how to pass my newly created instance of $template to the service.

when I run from the controller,

$this->templateManagerService->remove_all_modules_attached();

How does my service know which instance of template it needs to work with??

Jul
23
2 months ago
Activity icon

Started a new Conversation Editing Robots.txt

Hello,

I would like to edit the robots.txt in my CMS in a textarea input field. I am not quite sure how to access the file and load its content. I am using the laravel filesystem but the public and local drives do not point to the /public folder.

Should I create a new drive pointing to /public? Should I move my robots.txt to the public drive (/storage/app/public)? Should I get the content using PHP file functions (file_get_contents() / file_put_contents)?

I am just not quite sure how to approach this?

thanks

Jul
04
3 months ago
Activity icon

Started a new Conversation Editing Parts Of A Model From Multiple Screen & Logging

Hi,

I have a model called core_settings It has 2 fields. SiteName and Status I have 2 controllers. 1 to go to a screen to edit SiteName and the other one to go and edit the website status (live or maintenance) When saving each screen, the core_settings model's observer triggers the "updated" function where I want to log what has been saved. In both cases the core_settings model has been updated and logging the core settings has been updated is not enough. I need to log which screen has been updated. I do not really want to do it in the controller. Not in the repository either. I though the observer would be a good place to do it. Is it? or is there a better place to do it? Another way of doing what I am trying to do? I guess I can detect the page edited in the observer and log the relevant message.

Jun
29
3 months ago
Activity icon

Replied to Looking For A Some People To Build A CMS

@snapey

Hello,

I have indeed reviewed some of the most popular CMS listed in https://laravel-news.com/laravel-cms-packages . Looking at their respective demos, a couple of them looked good from the surface. Others seems too technical, or very much lacking documentation & examples.

I think my real motivation considering the level I am at, is to create a system with other people who want to learn Laravel with me, and have it mentored by someone who has an idea of how it should be architectured.

I have a pretty good idea of what feature we would need to build and the type of functionalities an end user requires to create a decent website.

I don't want to build something like October CMS. The closest thing I saw that matched my idea was "botble". It offers a lot of feature the vast majority of people would require and is intuitive. October CMS might be good for some people but last time I tried I just did not get it, and I would not think for an instant that any average end-user would understand how to manage it.

So is there a need for a new CMS? Maybe, maybe not... I can't really answer that. I am just looking for a team of people who would like to build a CMS alongside me and learn Laravel.

Jun
28
3 months ago
Activity icon

Started a new Conversation Looking For A Some People To Build A CMS

Hi everyone,

I am looking for some people who would be willing to take part in the development of a Laravel CMS. I initially wanted to build it all myself, but I am at a point where I am struggling to make decisions on some areas of the system and so I thought: " wouldn't it be nice if I could gather a small team and if we could share ideas, knowledge and best practice." Sounds nice.

Now, I am not an expert in Laravel but I have been playing with it for a year. I have 15 years expertise in IT and I have used systems like Drupal, Silverstripe,.... and an old custom CMS which I built a long while ago. Now, it's time to learn something new and Laravel is a nice framework to get my teeth into.

Personally, over the past year, I have been working by myself on a personal Laravel CMS project. The idea was to develop a system whilst learning the Laravel framework, which I did not know at all. I have been doing this after work and in the evening. I went online, going from tutorial to tutorial, reading articles, Youtube videos,.... there is a lot that still escapes me but I am at a point where think it would be nice to get involved with other developers and start on something fresh.

I need people quite driven who have some spare time. I know it is very difficult to commit everyday but if you have a few hours every week, then that's something.

You need to have a reasonable PHP/Mysql level and be able to create models, routes, controllers, databables, forms, middleware, views at a minimum. If you can do all of that, then that's great! Let's have a chat.

I also think it would be ideal if I could also find some people with a bit more experience who could guide us when problems arise.

Let me know if anyone is interested. I am based in Huddersfield in the UK

Jun
18
4 months ago
Activity icon

Started a new Conversation Getting Form Errors In Controller

Hi,

I am building a form with Tabs and if an error is returned, I want to highlight the Tabs that have issues inside them. At the minute, my code does no read the error messsages

    public function edit(Request $request)
    {

        $core_settings = CoreSettings::first();
        
        //checks policy
        $this->authorize('update', $core_settings);

        return view('rf-core-settings::rf-core-settings.core_settings.edit', compact('core_settings'));
  
    }


public function update(CoreSettingsStoreRequest $request)
    {

        //Calls the CoreSettingsStoreRequest where the policy check is done

        $core_settings = CoreSettings::first();  

        // Will return only validated data
        $validatedData = $request->validated();

        //updates the record
        $core_settings->update($validatedData);

        //redirects
        return redirect()->route('admin.dashboard')
                        ->with('success', trans('rf-core-settings::rf-core-settings.core_settings.messages.success_flash'));
    }

When an error occurs, I am redirected to the edit function in the controller and I was wondering if there was a function I could use to fetch my errors based on the code I am using.

I know I can use

$errors = Session::get('errors');

but I was wondering if there was something a bit more refined than going into the session directly.

I have read about bags and I ran little experiment with bags but that did not quite work.

    public function edit(Request $request, Illuminate\Support\ViewErrorBag $view_error_bag)
    {

        $core_settings = CoreSettings::first();
        
        //checks policy
        $this->authorize('update', $core_settings);

        $errors = \Session::get('errors');
        if (!empty($errors)){
              dd($errors);
              dd($view_error_bag);
        }

        return view('rf-core-settings::rf-core-settings.core_settings.edit', compact('core_settings'));
  
    }

The above displayed a bag with errors when using dd($errrors) But no errors in the bag when using dd($view_error_bag);

Any advice?

Jun
17
4 months ago
Activity icon

Started a new Conversation How To Pass Variable To Group Function / Lavary Menu

Hi,

The following code has been written using the lavary/laravel-menu. It feeds from the database where I have a nested tree.

//if the menu does not exist
if (! Menu::exists('DashboardMenu'))
{

	//create the dashboard enu
	Menu::make('DashboardMenu', function($menu){
		
		//loads the menu from the CMS tree. Descendant of Dashboard
		$cms_pages_tree = CmsPage::descendantsOf(2)->toTree();

		//loops items
		foreach($cms_pages_tree as $page)
		{

			$menu->add($page->label, ['route' => $page->route]);
			
			$menu->group(['style' => 'padding: 0', 'data-role' => 'navigation'], function($m){

				foreach($page->children as $child)
				{

					$m->add($child->label);

				}

			});
			
		}
		
	}

}

I have added the notion of 'Groups' to get data displayed in ULs and LIs. However, I do not know how to pass the $page variable (from the loop) into the $menu->group function

		//loops items
		foreach($cms_pages_tree as $page)
		{

			$menu->add($page->label, ['route' => $page->route]);
			
			$menu->group(['style' => 'padding: 0', 'data-role' => 'navigation'], function($m){

				foreach($page->children as $child)
				{

If I do

$menu->group(['style' => 'padding: 0', 'data-role' => 'navigation'], function($m, $page){

I get

ArgumentCountError
Too few arguments to function RF\RFCmsPages\Http\Middleware\GenerateCmsMenus::RF\RFCmsPages\Http\Middleware\{closure}(), 1 passed and exactly 2 expected
Jun
15
4 months ago
Activity icon

Started a new Conversation Yajra/eloquent Datatable Does Not Display Anything For BelongsTo Relationship Fields

Hi,

I have a belongs relationship I would like to display in a Yajrah datatable. I have the table working using DB but I want to get it to work using eloquent.

Working script using DB

 if ($request->ajax()) {

            $data = DB::table('log_activities')
                        ->join('admins', 'log_activities.admin_id', '=', 'admins.id')
                        ->whereIn('type', array('info'))
                        ->select(['log_activities.subject', 'log_activities.type', 'admins.first_name', 'admins.last_name', 'log_activities.created_at'])
                        ->latest();
            
            return Datatables::of($data)
                    ->addColumn('admin_name', function($row){
                        return $row->first_name.' '.$row->last_name;
                    })
                    ->setRowClass(function ($row) {
                        return $row->type; //The row class is set based on the log type 
                    })
                    ->make(true);
}

To change this for eloquent,

Migration

        Schema::create('log_activities', function (Blueprint $table) {
            $table->id(); //Alias of $table->bigIncrements('id')
            $table->string('subject', 5000);
            $table->string('url', 5000);
            $table->string('method',20);
            $table->string('ip',20);
            $table->string('agent')->nullable();
            $table->unsignedBigInteger('admin_id');
            $table->enum('type', ['info', 'notice', 'warning', 'error', 'critical', 'emergency'])->default('info');
            $table->timestamps();
        });

	Schema::table('log_activities', function($table)
        {
            $table->foreign('admin_id')->references('id')->on('admins');
        });



           Schema::create('admins', function (Blueprint $table) {
                $table->bigIncrements();
                $table->string('first_name');
                $table->string('last_name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
                $table->softDeletes();
            });

relationship


class LogActivity extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'subject', 'url', 'method', 'ip', 'agent', 'admin_id', 'type'
    ];


    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'id');
    }

}

controller

         
	$query = LogActivity::select(['subject', 'type', 'created_at')->with('admin:id,first_name,last_name')->get();
            
            return Datatables::of($query)
                    ->addColumn('admin_name', function($row){
                        return $row->first_name.' '.$row->last_name;
                    })
                    ->setRowClass(function ($row) {
                        return $row->type; //The row class is set based on the log type 
                    })
                    ->make(true);

view

<script>
$(function() {

    $('#logs-table').DataTable({
        paging: true, // Allow data to be paged
        searching: true, // Search box and search function will be actived
        ordering: true,

        lengthMenu: [[1, 10, 25, 50, -1], [1, 10, 25, 50, "All"]],
        pageLength: 10,

        autoWidth: true,
        
        dom: 'Blfrtip', //DOM variable for each element of the datatable
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ],

        processing: true,
        serverSide: true,

        ajax: '{!! route('admin.log.index') !!}',

        columns: [
            { data: 'subject', name: 'subject' },
            { data: 'admin_name', name: 'admin_name' },
            { data: 'created_at', name: 'created_at', orderable: false, searchable: false },
        ],

    });

});

</script>

I am not getting any error. I just get data displayed in admin_name column

In the below result, the admin relation does not return anything...

#items: array:17 [
    0 => RF\RFCmsLogs\Models\LogActivity {#1392
      #fillable: array:7 [
        0 => "subject"
        1 => "url"
        2 => "method"
        3 => "ip"
        4 => "agent"
        5 => "admin_id"
        6 => "type"
      ]
      #with: array:1 [
        0 => "admin"
      ]
      #connection: "mysql"
      #table: "log_activities"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:3 [
        "subject" => "Permission Group "Logs" has been created."
        "type" => "info"
        "created_at" => "2020-06-15 22:36:14"
      ]
      #original: array:3 [
        "subject" => "Permission Group "Logs" has been created."
        "type" => "info"
        "created_at" => "2020-06-15 22:36:14"
      ]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [
        "admin" => null
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [
        0 => "*"
      ]
    }

Any idea?

Just tried this

$records = LogActivity::all();

foreach($records as $r){
    print $r->admin->first_name;

}

and it works, so my belongsTo relationship must be properly setup...

May
27
4 months ago
Activity icon

Started a new Conversation Breadcrumbs Question

Hi,

Looks like this breadcrumb popular package is not maintained any more https://github.com/davejamesmiller/laravel-breadcrumbs

Is there any decent alternative around you can suggest?

May
25
4 months ago
Activity icon

Started a new Conversation How To Access A Custom Module Variable

Hi,

I have a custom module with variable

class MyTestProvider extends ServiceProvider
{
	public protected $module_name = "my-test";

In this very same service provider, I have controllers. How can my controller access the $module_name variable??

I tried to add in my controller constructor

print \Test\MyTestProvider::module_name;

but that does not work. It is looking for a constant which my variable is not...

Not sure what to do...

May
21
5 months ago
Activity icon

Replied to Authentication Question - 302 Code

@bugsysha Thanks for that. On the back if this, I am getting a little confused with the middleware of my dashboard routes

Route::group(['middleware' => ['web', 'auth:admin'], 'as' => 'admin.', 'prefix' => '/admin', 'namespace' => 'RF\RFCmsDashboard\Http\Controllers'], function()

The above works, but if I remove the 'web' middleware, the login page does not forward me to the dashboard page and only reloads the login page. That's confusing me.

Should 'web' always be added in route middleware? I have read in posts (https://laracasts.com/discuss/channels/laravel/middleware-web) that the web middleware was added automatically.

Activity icon

Started a new Conversation Authentication Question - 302 Code

Hi,

I am having issues with my authentication system. I am using laravel 7 and Laravel/UI

I had the following routes:

Route::prefix('/admin/')->name('admin.')->namespace('Admin\Auth')->group(function(){

    Route::get('login', '[email protected]')->name('login');
    Route::post('login', '[email protected]')
    Route::post('logout', '[email protected]')->name('logout');

    Route::get('password/reset', '[email protected]')->name('password.request');
    Route::post('password/email', '[email protected]')->name('password.email');
    Route::get('password/reset/{token}', '[email protected]')->name('password.reset');
    Route::post('password/reset', '[email protected]')->name('password.update');

    Route::get('password/confirm', '[email protected]')->name('password.confirm');
    Route::post('password/confirm', '[email protected]');

    Route::get('email/verify', '[email protected]')->name('verification.notice');
    Route::get('email/verify/{id}/{hash}', '[email protected]')->name('verification.verify');
    Route::post('email/resend', '[email protected]')->name('verification.resend');

});

I have a dashboard module with

Route::group(['middleware' => ['web', 'auth:admin'], 'as' => 'admin.', 'prefix' => '/admin', 'namespace' => 'RF\RFCmsDashboard\Http\Controllers'], function()
{
    
    App::setLocale(Session::get('lang'));

    Route::redirect('/', '/admin/dashboard');
    
    Route::get('dashboard','[email protected]')->name('dashboard');
    
});

I can not figure what is gong on. When I submit the login form. I get redirected to my dashboard upon authentication but I can see in my browser inspector a 302 error related to the login page with POST. The type of the request is type/html. It is followed by the dashboard page with a code 200.

Request URL: http://127.0.0.1:8000/admin/login
Request Method: POST
Status Code: 302 Found
Remote Address: 127.0.0.1:8000

I can display the name of user which indicates the user must have logged in successfuly. I use this code to display the user name

{{ Auth::guard('admin')->user()->first_name }}
May
09
5 months ago
Activity icon

Replied to Customising A Module

Hi @denniseilander

Thanks for the input. Are you suggesting I create the extended model in the App itself? I suppose I could do that... And then maybe have a configuration file for my package with a variable pointing to the Admin model I need to use. That might just work... What about the model form validation? obviously the new property is not in the Admin Request file. Would I need to extend that as well? It suddenly feels the parts of the package could be everywhere in the main App.

Is it possible to extend a package with another package??

Activity icon

Started a new Conversation Customising A Module

Hi,

I am writing a CMS working with modules and I have issues with the following scenario. Let's assume I have 2 websites and therefore 2 installations of the CMS. I have a 'Admin/Permission' module that manages administrators and permissions. if a bug is found, I can fix it and apply it to both systems using composer. That's easily done. My concern is more when one the system needs a customisation. Let's say after 6 month of usage, one the sites needs extra properties for the admin model. Updating the model, views... would have to be done but would be reflected in both CMS which we certainly don't want. What would be the best approach to allow this kind of flexibility ?

I am thinking of duplicating the 'Admin/Permission' module and customising it. Remove the current module, add the new module. Run a migration/seeding and all might still be working as before. But now I have 2 'Admin/Permission' module to maintain. Not great...

Any idea? suggestions?

May
03
5 months ago
Activity icon

Started a new Conversation URL Not Working

Hi,

I have setup the following routes.

/* ----------------------- Admin Routes START -------------------------------- */

/**
 * Admin Auth Route(s)
 */
Route::prefix('/admin/')->name('admin.')->namespace('Admin\Auth')->group(function(){

    //Login Routes
    Route::get('/login','[email protected]')->name('login');
    Route::post('/login','[email protected]');
    Route::post('/logout','[email protected]')->name('logout');

    //Forgot Password Routes
    Route::get('/password/reset','[email protected]')->name('password.request');
    Route::post('/password/email','[email protected]')->name('password.email');

    //Reset Password Routes
    Route::get('/password/reset/{token}','[email protected]')->name('password.reset');
    Route::post('/password/reset','[email protected]')->name('password.update');

});




//Runs with auth middleware
Route::prefix('/admin')->middleware('auth:admin')->name('admin.')->namespace('Admin')->group(function(){
    
    App::setLocale(Session::get('lang'));

    Route::get('dashboard','[email protected]')->name('dashboard');

    Route::get('home', '[email protected]')->name('home');

    Route::get('logs','[email protected]', ['only' => ['index'] ])->name('logs.index');

    Route::get('errors-log','[email protected]', ['only' => ['index'] ])->name('errorslog.index');

});

/* ----------------------- Admin Routes END -------------------------------- */

if I go to /admin/, I keep getting: The requested resource /admin/ was not found on this server.

I added in my route

    Route::redirect('/', '/dashboard');
    Route::get('','[email protected]');

but that does not help.

Is it because there is nothing after the second forward slash. Do I need to add a 301 redirect in the .htaccess??

Any idea?