FrazeColder

FrazeColder

Member Since 2 Years Ago

Experience Points
990
Total
Experience

4,010 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
2
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 1
990 XP
Oct
26
5 days ago
Activity icon

Started a new Conversation Do I Have To Write Tests For My Laravel Nova Code?

Hi Guys,

I am using Laravel Nova to administrate my users, posts, comments, etc. So, basically I coded a CMS for myself using Laravel Nova as my admin dashboard.

All the code I have written is PHPUnit tested except the code under app/Nova which is the code for the Nova dashboard. Now I wonder if I should write PHPUnit tests as well for this code as Laravel Nova comes as a tested package.

I am using the functions Nova is providing and some other functions/fields other packages for Nova are providing.

What do you say? I kind of see the point "you should test if the actions really do what you want" but also I think Laravel is a simple CRUD package which comes as a tested package. Means, If I set the database fields correct, everything should work like a charm without testing it.

What do you think?

Kind regards and thank you!

Oct
10
3 weeks ago
Activity icon

Replied to Request Validator For ISOString Date With Milliseconds

Any updates here on how do validate this ISO string?

Oct
01
4 weeks ago
Activity icon

Started a new Conversation Vue.js Components Test Or Laravel Dusk?

Hi, I want to test my Vue.js components but I don't know if I should use Laravel Dusk or Vue.js to test my components. I know it's possible to test the state of Vue components with Laravel Dusk as well..

However, what are the pros and cons on testing Vue components with Laravel Dusk or with Vue.js itself? Testing it with both, Laravel Dusk and Vue.js, wouldn't make sense I guess..

How do you see it?

Kind regards

Sep
22
1 month ago
Activity icon

Started a new Conversation Can PHP Traits Add Values To Protected Values Of The Model

Hi,

I am using Laravel 7 and at the moment I am trying to centralize some code by using PHP traits. However, I want to have traits which e.g. also add values to the protected $attributes variable or the protected $with variable.

Why I want that? Because I want to have code reuse and not to tell every Laravel model where I use my trait to also load the relationship and add the attributes to my model. That would be quite redundant...

I already figured out a way to add values to the protected $attributes variable. However, how can I add comments to my protected $with variable?

This is the code to add values to the protected $attributes variable:

    /* Add attributes to model $appends */
    protected function getArrayableAppends()
    {
        $this->appends = array_unique(array_merge($this->appends, ['publishedComments']));

        return parent::getArrayableAppends();
    }

Kind regards

Sep
19
1 month ago
Activity icon

Replied to Admin Needs To Approve Actions - Possible?

Hi at @jtanmay sadly not.. If you find any idea on how to do this please tell me!

Sep
18
1 month ago
Activity icon

Started a new Conversation ID Field Is Not Being Displayed (after Larave Update From 6.x To 7.x And Nova 2.x To 3.x)

Hi,

I have updated Laravel from 6.x to 7.x and Nova from 2.x to 3.x yesterday. However, since I did that the ids are not being displayed at the tables on Nova anymore when using ID::make(). Not even ID::make('ID', 'id'), ID::make()->asBigInt() or ID::make('ID', 'id')->asBigInt() is working and I don't know why.

This affects all my Nova models and not the one I am posting here. This is just an example model because it's quite slim.

Any ideas why Nova cannot resolve the ids of my model? When using Text::make('ID', 'id') I see the id. But why not with ID::make()?

Here is my model:

namespace App;

use Gwd\SeoMeta\Traits\SeoSitemapTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Gwd\SeoMeta\Traits\SeoMetaTrait;

class Page extends Model
{
    use SeoMetaTrait, SeoSitemapTrait;

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($page) {
            if (!$page->user_id){
                $page->user_id = Auth::id();
            }
        });
    }

    /**
     * @Protected_variables
     */

    protected $table = 'pages';

    protected $guarded = ['id'];

    protected $casts = [
        'publish_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * @Public_variables
     */

    /**
     * @Relationships
     */

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function pageStatus()
    {
        return $this->belongsTo('App\PageStatus');
    }

    public function pageType()
    {
        return $this->belongsTo('App\PageType');
    }

Here is my Nova model:

<?php

namespace App\Nova;

use Epartment\NovaDependencyContainer\HasDependencies;
use Epartment\NovaDependencyContainer\NovaDependencyContainer;
use Froala\NovaFroalaField\Froala;
use Gwd\SeoMeta\SeoMeta;
use Illuminate\Http\Request;
use Inspheric\Fields\Indicator;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\DateTime;
use Pdewit\ExternalUrl\ExternalUrl;
use App\PageStatus;

class Page extends Resource
{
    use HasDependencies;

    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = \App\Page::class;

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'title';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'title',
        'slug'
    ];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),

            Text::make('Title')
                ->rules('required', 'max:255'),

            ExternalUrl::make('Product Link', 'slug')
                ->onlyOnDetail(),

            Text::make('Slug', 'slug')
                ->hideFromIndex()
                ->creationRules('unique:pages,slug')
                ->rules('required', 'alpha_dash', 'max:80'),

            Froala::make('Content')
                ->hideFromIndex()
                ->rules('required'),

            Indicator::make('Status', function() {
                return $this->pageStatus->status;
            })
                ->labels([
                    'publish' => 'Publish',
                    'future' => 'Future',
                    'draft' => 'Draft',
                    'pending' => 'Pending',
                    'private' => 'Privat'
                ])
                ->colors([
                    'publish' => 'green',
                    'future' => 'purple',
                    'draft' => 'blue',
                    'pending' => 'orange',
                    'private' => 'red'
                ]),

            BelongsTo::make('Status', 'pageStatus', 'App\Nova\PageStatus')
                ->onlyOnForms(),

            NovaDependencyContainer::make([
                DateTime::make('When to Publish', 'publish_at')
                    ->format('DD.MM.YYYY @ HH:MM:SS')
                    ->rules('required', 'date_format:Y-m-d H:i:s')
            ])->dependsOn('pageStatus', PageStatus::getIdByStatus('future')),

            BelongsTo::make('Type', 'pageType', 'App\Nova\PageType')
                ->viewable(false)
                ->sortable(),

            BelongsTo::make('User', 'user'),

            SeoMeta::make('SEO', 'seo_meta'),
        ];
    }

    /**
     * Get the cards available for the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function cards(Request $request)
    {
        return [];
    }

    /**
     * Get the filters available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function filters(Request $request)
    {
        return [];
    }

    /**
     * Get the lenses available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function lenses(Request $request)
    {
        return [];
    }

    /**
     * Get the actions available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function actions(Request $request)
    {
        return [];
    }
}

Here is my migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('pages', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedBigInteger('user_id')->index();
            $table->char('title')->index();
            $table->char('slug')->index()->unique();
            $table->text('content');
            $table->unsignedBigInteger('page_type_id')->index();
            $table->unsignedBigInteger('post_category_id')->index()->nullable();
            $table->unsignedBigInteger('page_status_id')->index();
            $table->timestamp('publish_at')->nullable();
            $table->softDeletesTz();
            $table->timestamps();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('restrict');

            $table->foreign('page_type_id')
                ->references('id')
                ->on('page_types')
                ->onDelete('restrict');

            $table->foreign('post_category_id')
                ->references('id')
                ->on('post_categories')
                ->onDelete('restrict');

            $table->foreign('page_status_id')
                ->references('id')
                ->on('page_statuses')
                ->onDelete('restrict');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('pages');
    }
}

Kind regareds

Sep
03
1 month ago
Activity icon

Replied to Laravel Socialite Register User With Social Account And Force Them To Pick A Username

I do know that. However, I want the user to be able to set an own nickname because the nickname provided by Facebook or Google mostly like is the first and last name.

Activity icon

Started a new Conversation Laravel Socialite Register User With Social Account And Force Them To Pick A Username

I want to give users the opportunity to login/register via social login (like Facebook or Google). In order to do this I am using the package Socialite provided by Laravel.

I also give the users the opportunity to register by email and password. When doing so they have to choose a username as well. So far so good. Here is no problem because when the user gets created he has submitted a username, a email address and a password.

However, when doing this via social login the user has not chosen a username. I just get the name of the user from Google or Facebook but that's not what I want. I want the user to choose a username/nickname.

The problem is that the username is not nullable because I am using implicit binding on my username for the user model.

Right now I am bypassing this problem by putting the email, provider and provider_id I get from the social login in the user session. Whenever the user session contains those 3 parameters I show a form to the user where he has to choose a username. When submitting the form the user gets created by the username provided from the form and the email, provider and provider_id from the session.

Another possible solution is to make username nullable in the database and store the email, provider and provider_id right away when doing the social login and setting the username to null. This would solve the problem of having a session conflict but I would have a empty username in my database which would lead to many other problems as username is my key for the implicit route binding. I don't really favor this solution too but it is one possible solution.

My question to you is now what better way to do this is there? My favorite way would be to pass the email, provider and provider_id to the ProductController@index` as PHP variables because they cannot be manipulated! However, I haven't found any solution on how to do this except doing this via sessions.

Here is my sourcecode so far:

SocialLoginController

class SocialLoginController extends Controller
{

    public function redirect($provider)
    {
        return Socialite::driver($provider)->redirect();
    }

    public function callback($provider)
    {
        $getInfo = Socialite::driver($provider)->user();

        $user = $this->userExists($getInfo);

        if(!$user){
            $user = array();
            $user['email'] = $getInfo->email;
            $user['provider'] = $provider;
            $user['provider_id'] = $getInfo->id;
            $user['avatar'] = $getInfo->avatar_original;

            Session::put('user', $user);
            return redirect()->to(route('home'));
        }

        auth()->login($user);

        return redirect()->to(route('product.index'));

    }

    function createUser(SocialRegisterUserRequest $request)
    {
        //TODO: Avatar
        //TODO: Username

        $userSession = Session::get('user');

        $user = User::create([
            'name' => $request->name,
            'email' => $userSession['email'],
            'email_verified_at' => date('Y-m-d H:i:s'),
            'provider' => $userSession['provider'],
            'provider_id' => $userSession['provider_id']
        ]);

        Session::flash('user');

        auth()->login($user);

        return redirect()->to(route('product.index'));
    }
}

web.php (routes)

Route::get('/auth/redirect/{provider}', '[email protected]');

Route::get('/callback/{provider}', '[email protected]');

Route::post('/social/register', ['as' => 'social.register', 'uses' => '[email protected]']);

Some explanation for you: When doing a social login the user calls the route [email protected]. This passes to request to the redirect function. When the user has approved the social login for my app on Facebook or Google he will be redirected to the callback function. Here he checks if the user already exists. If so, he gets logged in if not the data are put into the session. Now the form for choosing a username will be shown to the user. When he submits this form he will be routed to the createUser function which then finally creates the user.

Any ideas on how to do this in a better way? I am grateful for any kind of help!

Kind regards

Aug
30
2 months ago
Activity icon

Started a new Conversation Use Laravel Socialite Register User And Redirect To Form To Fill Out More Data?

Hi guys,

I have implemented Laravel Socialite with Google today as described in this article. So far so good, everything is working.

However, I want to do a few changes and customize the process of registering users who login the first time via social networks. My Laravel project is working with nicknames like in forums. Of course these nicknames have to be unique.

My goal is now to redirect users who login via social networks for the first time to a form where they can enter a nickname and when this form gets submitted the user gets created. I am a little bit screwed on how I am going to implement this and need your advice.

The problem is, I have to fetch the data from e.g. Google, redirect the user to a form where he enters his nickname and submits the form. But this form has to include all data, also the data which I got from Google in order to create a user with nickname, email, avatar, provider (e.g. google, facebook, etc.) and provider id.

I haven't pasted any code here now because my code looks exactly the same as described in the article above I linked!

Kind regards!

Aug
27
2 months ago
Activity icon

Started a new Conversation Laravel Route Model Binding With Sorted Eager Loading?

I have products which have also comments. This comments can be voted and comments can also have child comments. The comments get loaded via eager loading $with which is defined in the product model and the child comments get as well loaded via eager loading which is also defined in the comments model. The child comments can also be voted (but don't have any child comments).

Product.php (Model)

namespace App;

class Product extends Model
{
    /**
     * @Protected_variables
     */

    protected $with = [
        'comments',
        'user'
    ];

    /**
     * @Relationships
     */

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

Comment.php (Model)

namespace App;

class Comment extends Model
{
    /**
     * @Protected_variables
     */
     
    protected $with = [
        'children',
        'user'
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function children()
    {
        return $this->hasMany('App\ChildComment');
    }
        
    public function likes()
    {
        return $this->belongsToMany('App\User', 'comments_likes', 'comment_id', 'user_id')->withTimestamps();
    }
}

I use route model binding to receive my product in the ProductController. Here is an example of the route Route::get('/product/{product}', ['as' => 'product.show', 'uses' => '[email protected]']); and the function show:

[email protected]:

public function show(Product $product, Request $request)
{
    if(request()->wantsJson()){
        return response()->json([
            'product' => $product
        ]);
    }

    return view('pages.productDetails')->with([
            'product' => $product
        ]);
}

In the show function I can now access the comments of the product, as well as the child comments of the comments and all the other relations which get loaded via the $with attribute in the models.

Now comes questions. As I already have loaded the relationship, how can I either 1. sort them now or 2. pass the sort arguments to the model to get a sorted relationship back?

When I write dd($product->comments->sortByDesc('created_at')->toArray()); I get my product with the comments which are sorted by created_at. That's what I want. But I cannot assign the sorted collection to the product collection like this $product->comments = $product->comments->sortByDesc('created_at'); because $product->comments is @property-read.

I also don't want to do another query and pass this $product->comments()>orderBy('created_at', 'desc')->get(); to my response. Because then the eager loading in the model redundant.

Is there a way to 1. either sort the relationship collection or 2. pass the sort arguments to the model to get a sorted relationship back?

I actually want to stick to my route binding model. I know I could pass the sorting arguments and product id as arguments and then execute it via get. But is there a solution to do that within the model eager loading?

Also, please note I want to sort my comments also by likes and the count of child comments they have. I don't want to sort them only by date, so I need to pass the sort argument to the model when choosing a solution for number 2.

Kind regards!

Aug
26
2 months ago
Activity icon

Started a new Conversation Laravel Eager Loading Sort By Count Of Relationship Entries/values

I have products which have also comments. This comments can be voted and comments can also have child comments.

Now I want to sort these comments by date, amount of likes and amount of child comments.

Before I show you my tries I will show you my code:

Product.php (Model)

namespace App;

class Product extends Model
{
    /**
     * @Protected_variables
     */

    protected $with = ['comments', 'user'];

    /**
     * @Relationships
     */

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function comments()
    {
        return $this->morphMany('App\Comment', 'commentable');
    }
}

As you can see, I already tell Laravel with the variable $with to load comments and user always when loading a product.

ProductController.php

public function show(Product $product, Request $request)
{
    if($request->has('sorting') && in_array($request->sorting, ['Beliebtesten', 'Diskutiertesten', 'Neusten'])){
        if($request->sorting == 'Neusten'){
            $product->load(['comments' => function ($query) {
                $query->orderBy('created_at', 'desc');
            }]);
        }else if($request->sorting == 'Diskutiertesten'){
            $product->load(['comments.children' => function ($query) {
                $query->orderBy('published_date', 'asc');
            }]);
        }else{
            $product->load('comments')->get()->sortByDesc(function($product)
            {
                return $product->likes->count();
            });
        }

        return response()->json([
            'product' => $product
        ]);
    }else{
        $product->load('comments');

        return response()->json([
            'product' => $product
        ]);
    }
}

So, I have two questions now:

  1. Do I even need $product->load('comments')? - Because I have figured out when I just pass the $product without executing $product->load('comments') I also have the comments loaded... Looks like I don't need it. Is that right?

  2. How can I sort the comments by amount of likes (rows, because you can only upvote) and by amount of child comments (rows)?

This is what I have tried so far (all not working for me):

$product->load('comments')
    ->withCount('likes')
    ->orderBy('likes_count','DESC')
    ->get();
$product->loadCount('comments');

$product->orderBy('comments_count', 'desc');
Aug
14
2 months ago
Activity icon

Started a new Conversation Vue Js Infinit Scroll Disable After Page 3 And Replace With “load More” Button?

I want to implement an infinity scroll for my Vue js app. However, this infinity scroll should only load x times when hitting the bottom of the page. In my case I want the infinity scroll to load more content only for the first 3 times the user hits the bottom and then the infinity scroll should display a "load more" button and only load more content if the user clicks on this "load more" button.

I haven't implemented anything yet but I want to know what would be your Vue js infinity scroll package to go and why? How would you solve this?

There are two good infinity scroll packages for Vue js. The more famouse vue-infinite-loading and the vue-infinite-scroll package.

I have already checked the documentation of both packages but sadly I haven't found a build in function for this case. How would you implement this? Maybe another package?

Kind regards and thank you!

Jul
16
3 months ago
Activity icon

Started a new Conversation Optimize Ram Usage Laravel, Split Cronjobs Into Chunks?

I have a Laravel backend which is fetching data from various APIs every day and processing them. There is one command for fetching those data and storing them in the database and one command which is using these data to update wordpress fields. This is because laravel is just the backend for the for my wordpress site and laravel takes care of updating fields of my online shop.

At the moment there are 16.000 products online. So the command which uses the fetched and stored data from the database to update fields in wordpress has to go through 16.000 products in order to update the fields of each product. But here comes now the problem. I have a ram limit of 128Mb by my hoster. But to finish the task of updating the fields of wordpress I need about 280Mb. You can see this here on the figure:

enter image description here

The blue line represents a script where I fetch all the fields and products to update via a raw SQL statement and the orange represents a script where I use a laravel model to process the fields I want to update. Everything besides the SQL statement and the laravel model is the same!

As you can see the SQL statements starts off with less MB but is not as efficient with a large amount of products as the version which is using a laravel model to process the data. The script which is using the laravel model is slightly better.

The version which is using the laravel model to process the data is using the laravel chunk method to split up the models. I guess this is also the answer to the small gaps on the orange line.

My question now is if there is the possibility to chunk the products I want to process before the script gets executed? In this way the garbage collector can remove the data from the script before which has processed a chunk of data and the ram gets cleaned.

Is there a possibility to set up a cron which is processing 0-5000 products, the next one 5000-10000 products and so on and so on. If so, how can I implement this? Will the garbage collector also remove all variables from the ram which where used in the script before?

I will also paste you my code below here but I don't think its really helpful. Any ideas are welcome to minimize the ram usage!

Code of the script which is using laravel models:

public function handle(UpdateFields $updateFields, UpdateStatus $updateStatus, UpdateTerms $updateTerms)
{
  $count = 0;
  $chunkSize = 5000;
  $countProducts = Post::lastProductId();

  while($count < $countProducts){
      $products = Post::allProductsLiveWithMetas($count, $chunkSize);
      
      // Loop trough each product
      foreach($products as $product){
          // Update fields
          $updatedFields = $updateFields->setProduct($product)->update();

          // Update Status
          $status = $updateStatus->setProduct($product)->update();

          // Update Terms
          // Update Gender
          $gender = $updateTerms->setProduct($product)->set_gender();

          // Update Size
          $size = $updateTerms->setProduct($product)->set_size();
          
          // Update Sale
          $sale = $updateTerms->setProduct($product)->set_sale();

          // Delete Wordpress Cache to save from memory leakage
          wp_cache_delete($product->ID, 'post_meta');

          unset($product);
          unset($updatedFields);
          unset($status);
          unset($gender);
          unset($size);
          unset($sale);
      }

      unset($products);
      $count = $count + $chunkSize;
  }
}

Kind regards

May
15
5 months ago
Activity icon

Replied to Admin Needs To Approve Actions - Possible?

That is also an idea I have. But now comes to question: Is it possible to have a beautiful compare of before and after in Laravel Nova? Like the action log in Laravel Nova. If you click on details you have a beautiful listing of what have been changed.

Is it possible to have such a listing to for what is requested to change?

Activity icon

Started a new Conversation Admin Needs To Approve Actions - Possible?

Hi, Laravel Nova is providing actions out of the box. However, I would like to modify those actions slightly.

I want to have the possibility to approve actions before they go live. For example: I have users and posts which I manage in my Laravel Nova dashboard and in the resources. Now I would like to give the user the possibility to edit his post. The user is not using Laravel Nova, the User has a normal fronted.

However, I would like to have the possibility to review the changes which were made before I approve the post. So, the changes need to be stored in the database without being online. Is this possible or do I need to implement this by myself?

Kind regards!

Apr
29
6 months ago
Activity icon

Awarded Best Reply on Spatie Media Library Upload ALWAYS Leads To “request Does Not Have A File In A Key Named […]”

I finally found my error. My system is running on a Mac with Catalina. The problem is that I was hosting my project locally with php artisan serve. For some reason there where a problem with the permission to access the temp folder.

I am now running on valet without any hassle or error... maybe it's gonna help someone!

Activity icon

Replied to Spatie Media Library Upload ALWAYS Leads To “request Does Not Have A File In A Key Named […]”

I finally found my error. My system is running on a Mac with Catalina. The problem is that I was hosting my project locally with php artisan serve. For some reason there where a problem with the permission to access the temp folder.

I am now running on valet without any hassle or error... maybe it's gonna help someone!

Activity icon

Replied to Spatie Media Library Upload ALWAYS Leads To “request Does Not Have A File In A Key Named […]”

It could be that this is my error. How can I check of my avatars media collection exists and furthermore how can I create one?

Apr
28
6 months ago
Activity icon

Started a new Conversation Spatie Media Library Upload ALWAYS Leads To “request Does Not Have A File In A Key Named […]”

I have installed Spatie Media Library exactly how it is described on their docs. However, every time I try to save a media file with addMediaFromRequest('keyName') I get this error:

The current request does not have a file in a key named keyName

Every installation and getting started guide, such as this one on Laravel-News.com, is telling me to put this in my controller:

if (isset($data['avatar'])) {
    $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');
}

That's also what I have done. Nevertheless I still get this "... request does not have a file ..." error... which really annoys me. I follow exactly the instalttion guides but it is not working.

This is how my Models, Controllers and View looks like for the registration procedure:

User.php:

use Glorand\Model\Settings\Traits\HasSettingsField;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\Models\Media;

class User extends Authenticatable implements HasMedia
{
    use Notifiable;
    use HasRoles;
    use HasSettingsField;
    use HasMediaTrait;
    
    // ...
}

RegisterController.php (Note my // comments):

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);

    //If I check, if the avatar is set, I create a user without avatar
    if (isset($data['avatar'])) {
        $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');
    }

    //If I don't check it, it leads to "... request does not have a file ..." error
    $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');

    return $user;
}

register.blade.php:

// ...
<div class="form-group row">
    <label for="avatar" class="col-md-4 col-form-label text-md-right">{{ __('Avatar (optional)') }}</label>

    <div class="col-md-6">
       <input id="avatar" type="file" class="form-control" name="avatar">
    </div>
</div>
// ...

The same also goes for other controllers where I want to give the possibility to upload avatars. For example my UserController leads to the same problem.

UserController.php

// ...
public function update(Request $request, User $user)
{
    if (isset($request->avatar)) {
        $user->addMediaFromRequest('avatar')->toMediaCollection('avatars');
    }
}
// ...

However, if I dump the $request->avatar it is not empty! That actually MUST mean, that $request->avataris not empty BUT addMediaFromRequest('avatar') simply cannot access this variable or is trying to access another variable instead of the $request->avatar variable. The result I get when I dump $request->avatar:

Illuminate\Http\UploadedFile {#473 ▼
  -test: false
  -originalName: "23133.png"
  -mimeType: "application/octet-stream"
  -error: 1
  #hashName: null
  path: ""
  filename: ""
  basename: ""
  pathname: ""
  extension: ""
  realPath: "/Users/myname/Desktop/Coding/MyProject/public"
  aTime: 1970-01-01 00:00:00
  mTime: 1970-01-01 00:00:00
  cTime: 1970-01-01 00:00:00
  inode: false
  size: false
  perms: 00
  owner: false
  group: false
  type: false
  writable: false
  readable: false
  executable: false
  file: false
  dir: false
  link: false
}