Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

Neeraj1005

Neeraj1005

Member Since 1 Year Ago

Experience Points
31,200
Total
Experience

3,800 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
143
Lessons
Completed
Best Reply Awards
1
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 7
31,200 XP
Nov
21
4 days ago
Activity icon

Started a new Conversation Livewire\Exceptions\PropertyNotFoundException Property [$searchItem] Not Found On Component: [landing-page.right-sidebar]

In my project my trying to make a search box. But I have two livewire component one in list-post part and another is right-side-bar.

Imgur

This is my list-posts.blade

<div>
    <div class="row featured-post-heading">
        <div class="col-md-12 mt-5 mb-3">
        </div>
     </div>
     <div class="row">
        <div class="col-md-9 pl-0 pr-5">
            @forelse($list_of_posts as $post)
            <div class="col-md-12 border-bottom pb-3 mb-3">
                <div class="media">
                    <img src="{{ optional($post->featured_image)->getFullUrl() ?? $post->default_image }}" width="175" class="mr-3 img-fluid rounded" alt="{{ $post->slug }}">
                    <div class="media-body">
                        <h5 class="mt-0"><a href="{{ route('post.viewitem', $post->slug) }}">{{ $post->title }}</a></h5>
                        <div class="blog-info mb-3"><span>{{ $post->created_at->toFormattedDateString() }}</span> <span>{{ $post->category->name }}</span></div>
                            <p>{!! $post->summary_of_body !!}</p>
                        </div>
                </div>
            </div>

            @empty
             <h3>No Posts Available</h3>
            @endforelse
            {{ $list_of_posts->links() }}
        </div>

	{{-- This is right-sidebar-component --}}
        <livewire:landing-page.right-sidebar :searchItem="$searchItem"/>

     </div>
</div>

And this is my Right-sidebar.blade

<div>
        <div class="mb-4">
            <h6 class="mb-4">Search</h6>
            <div class="input-group">
                <input wire:model.debounce.300ms="searchItem" type="text" class="form-control" placeholder="Search for...">
            </div>
        </div>

        <div class="mb-4">
            <h6 class="mb-4"><a href="{{ route('lists_of_category') }}">Categories</a></h6>
            @forelse ($blog_categories as $cat)
            <p class="border-bottom pb-2 mb-2"><a href="{{ route('latest.latestpost',['category' => $cat->name]) }}">
                <i class="fas fa-chevron-right"></i> {{ $cat->name }} [{{ $cat->category_has_total_posts() }}]</a></p>
            @empty
            <p><a href="#">{{ __('No Categories Available') }}</a></p>
            @endforelse
        </div>
</div>

And this is main ListPostComponent

<?php

namespace App\Http\Livewire\LandingPage;

use App\Post;
use Livewire\Component;
use Livewire\WithPagination;

class ListPosts extends Component
{
    use WithPagination;

    public $searchItem = '';

    protected $paginationTheme = 'bootstrap';

    public function render()
    {
        $lists_of_posts = Post::categoryFilter(request('category'))
                                ->tagFilter(request('tags'))
                                ->popularFilter(request('blogs'))
                                ->featuredFilter(request('blogs'))
                                ->search($this->searchItem)
                                ->orderBy('id', 'desc')->paginate(10);
        return view('livewire.landing-page.list-posts', [
            'list_of_posts' => $lists_of_posts,
        ]);
    }
}

Nov
18
1 week ago
Activity icon

Started a new Conversation ErrorException Undefined Index: Name Http://acl.test/newsletter/imports

In my project I've used the https://github.com/maatwebsite/Laravel-Excel package for importing the data. The problem I am facing that: If I upload correct file with correct header or row data File succesfully uploaded. But if I put wrong file with wrong data it sends me an error.

Can anyone tells me how can I validate the proper validation for csv If i put wrong file then it show me an error?

Import File

<?php

namespace App\Imports;

use App\Newsletter;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class NewsletterImport implements ToModel, WithHeadingRow, WithValidation
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new Newsletter([
            'name'     => $row['name'],
            'email'    => $row['email'],
            'token'    => Str::random(60),
        ]);

    }

    public function rules(): array
    {
        return [
            '*.name' => ['name', 'unique:newsletters,name'],
            '*.email' => ['email', 'unique:newsletters,email'],
        ];
    }
}

Rules

 public function rules()
    {
        return [
            'import_file' => 'required|file|mimes:csv,txt,xls',
        ];
    }

Export Controller

 public function store(NewsletterImportRequest $request)
    {
        if ($request->hasFile('import_file')) {
            $import_file = $request->file('import_file');
        }

        Excel::import(new NewsletterImport, $import_file);

        return back()->withMessage('file successfully imported');
    }

Nov
16
1 week ago
Activity icon

Replied to Laravel Queue Not Working On Deployment

can you tells me how to install supervisor in shared hosting(cpanel)...? because I'm facing the same problem..

Activity icon

Replied to Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed: Threads.user_id (SQL: Insert Into "threads" ("user_id", "title", "body", "updated_at", "created_at")

@tykus I don't understand 'First problem is the action is not auth protected because typo:'

@shaungbhone because you misspelled the __contstuct function fixed this __construct. As @tykus said.

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

php artisan queue:work

I want to get rid of this instead of using terminal. I want run this command automatically in background.

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@martinbean so I've to install and find how to install supervisor in shared hosting...right ?

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@martinbean @tykus I google this problem but I found most of them said that set the cronJob in shared hosting. https://stackoverflow.com/questions/52273132/how-to-run-queue-worker-on-shared-hosting?noredirect=1&lq=1 Is it a good way to setup the crone Job for queue?

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@tykus ohh thank you! its sync i mispelled this.

install services

Which services I've to installed. supervisor?

Activity icon

Replied to Laravel Queue:work Setup In Background Cpanel

@martinbean So, in cpanel I have to install supervisor and SSH? Do you have any idea how this can be resolve...? SO instead of database should I have to use sync

QUEUE_CONNECTION=sync

Activity icon

Replied to Laravel Queue Not Working On Deployment

@isadma can you tell me how queue works in production.... basically for running the queue I have to run queue:work in terminal that is very annoying can you tell me how can i run queue:work without terminal?

Make sure your app is not in maintenance mode... Queue doesn't work in maintenance mode.

Activity icon

Started a new Conversation Laravel Queue:work Setup In Background Cpanel

In my project I've made a simple newsletter system where I want to send an email to all subscriber. But the problem I faced in production (cpanel hosting) I have to run laravel queue:work command in terminal. Can anyone tells me how to handle queue:work in background in cpanel hosting... It would be very appreciable...can anyone tell me how to handle this problem?

ANd using the laravel queue database connection For sending the mail I'm using the shared hosting email smtp. Not using the mailchimp or mailgun etc...

Nov
09
2 weeks ago
Activity icon

Replied to Best Practice Way To Define Category Table For Other Related Many To Many Tables

@marianomoreyra yes! many-to-many polymorphic relations would be best for @marianomoreyra case.

Activity icon

Replied to Best Practice Way To Define Category Table For Other Related Many To Many Tables

@marianomoreyra If you want to use one categories table for products and posts. You can use Polymorphic Relationships => oneToMany OR manyTomany It depends on you and your outcomes.

Activity icon

Started a new Conversation Package Fzaninotto/faker Is Abandoned, You Should Avoid Using It. No Replacement Was Suggested.

Today I tried to update my project then I got this warning.

Package fzaninotto/faker is abandoned, you should avoid using it. No replacement was suggested.

So my question is? In upcoming laravel version faker will be used or not?

Activity icon

Replied to Unable To Display Raw Html Data In Blade File Using Substr Function

@shariff In your model use accessor like this

  public function getSummaryOfDescriptionAttribute()
    {
        $description=  Str::limit(strip_tags($this->body), 156, '...');
        
        return $description;
    }

https://www.php.net/manual/en/function.strip-tags.php

And in your blade file do this

<p>{!! $blog->summary_of_description ?? '' !!}</p>
Activity icon

Started a new Conversation ErrorException Undefined Variable: Blogs (View: /home2/study6/public_html/cms/resources/views/components/homepage/blog-component.blade.php)

This is the error

ErrorException
Undefined variable: blogs (View: /home2/study6/public_html/cms/resources/views/components/homepage/blog-component.blade.php)

In my welcome.php file I'm trying to fetch the all blogs using component. In my local environents the code perfectly runs but In my production server it throw an error. Can anyone tells me whats the problem? component class app\View\Components\homepage\BlogComponent.php

<?php

namespace App\View\Components\homepage;

use App\Post;
use Illuminate\View\Component;

class BlogComponent extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|string
     */
    public function render()
    {
        return view('components.homepage.blog-component',[
            'blogs' => Post::whereIsactive(1)->get(),
        ]);
    }
}

this is the blade view views/components/homepage/blog-component.blade.php

<div>
    <div class="row">
        @forelse($blogs as $post)
        <div class="col-md-4">
            <div class="latest-post border mb-4">
                <a href="#">
                    <img src="{{ optional($post->featured_image)->getFullUrl() ?? $post->default_image }}" class="img-fluid" alt="{{ $post->slug }}">
                </a>
                <div class="card-body">
                    <h5 class="c-title"><a href="#">{{ $post->title ?? '' }}</a></h5>
                    <div class="blog-info mb-3">
                        <span>{{ $post->created_at->toFormattedDateString() }}</span>
                        <span>{{ $post->category->name ?? '' }}</span></div>
                    <p>{!! $post->summary_of_body ?? '' !!}</p>
                </div>
                <div class="card-footer small bg-light">
                    <a class="float-left read-more-arrow" href="#">Read More <i class="fa fa-angle-double-right" aria-hidden="true"></i></a>
                    <a class="float-right" href="#"><i class="fa fa-comments-o" aria-hidden="true"></i> 0</a>
                </div>
            </div>
        </div>
        @empty
        <div class="col-md-12 bg-dark-two statistics text-center text-white">
            <h4>No blogs Available</h4>
        </div>
        @endforelse
    </div>
</div>

and This is the main route web.php

 Route::get('/', function () {
        return view('welcome');
    });

Nov
08
2 weeks ago
Activity icon

Replied to What Is Wrong With My Edit Function/form?

@robinmvdoorn is the error still persist?

Edited Is your Url correct? please check documentation https://laravel.com/docs/8.x/controllers#resource-controllers

Route::resource('books', BooksController::class);

Activity icon

Replied to Tag Updating (comma-separated Tag) Issue In APP

@silencebringer Now this error comes. Is this updateOrCreate correct?

SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'tag12' for column 'tag_id' at row 1 (SQL: insert into `post_tag` (`post_id`, `tag_id`) values (4, tag12))

Activity icon

Replied to What Is Wrong With My Edit Function/form?

@robinmvdoorn Can you update your code like this? and check what is your wildcard route parameter name is books OR book Run command in cli php artisan route:list --path=books

public function update(Request $request, Book $books)
    {
        $validatedData = $request->validate([
            'title' => 'required',
            'author' => 'required',
            'description' => 'required',
            'image' => 'required',
            'category' => ['exists:categories,id'],
        ]);

        $books->update($validatedData);
       

        return redirect(route('books.index'));
    }
Activity icon

Replied to Tag Updating (comma-separated Tag) Issue In APP

@silencebringer now this error occurs ErrorException Illegal offset type for this

$post->tags()->sync($tags);

Activity icon

Replied to Tag Updating (comma-separated Tag) Issue In APP

@silencebringer

{{ $post->tags->keyBy('name')->keys()->implode(', ') }} THis one is working

Now my tag part is not updating only one value is update for e.g: suppose I've post with tags: tag1,tag2,tag3 If I updating the post like tag1,tag2,tag3,tag4 only tag4 is sync or other tags are removed. If i dd() the tags only one tag is showin. can you please tell me what the problem?

#this is my updating tag code
 if (request('tags') != '') {
            $tags = explode(',', request('tags'));
            // dd($tags);
            foreach ($tags as $tag_name) {
                dd($tag_name);
                $tag = Tag::updateOrCreate(['name' => $tag_name]);
                // dd($tag);
                $post->tags()->sync($tag);
            }
        } 
Activity icon

Replied to What Is Wrong With My Edit Function/form?

@robinmvdoorn can you show your Book model? and did you tried dd() your value?

just tried 
dd($books);
OR
dd($request->all());
// $books->save();
Activity icon

Replied to What Is Wrong With My Edit Function/form?

@robinmvdoorn you missed the enctype="multipart/form-data"

<form method="post" action="{{route('books.update', $book->id)}}" enctype="multipart/form-data">

you are using the image.

Activity icon

Started a new Conversation Tag Updating (comma-separated Tag) Issue In APP

In my project Now I want to create tag when post is created or tag updated when post is update. But the problem I face in updating part creating tag with post is working nice but while updating the post only one tag is updated I don't know what the problem can anyone solve this issue updating the tag while updating the post. THis is my controller method

controller

    public function store(PostStoreRequest $request)
    {
        // dd(request('postType'));

        $input = $request->validated();

        $postType = $request->postType; #check Post is draft or published

        switch ($postType) {
            case 'draft':
                $input['published'] = false;
                break;

            default:
                $input['published'] = true;
                break;
        }
        // dd($input['published']);

        $posts = auth()->user()->posts()->create($input);
        // dd(request('tags'));
        if (request('tags') != '') {
            $tags = explode(',', request('tags'));
            foreach ($tags as $tag_name) {
                $tag = Tag::firstOrCreate(['name' => $tag_name]);
                $posts->tags()->attach($tag);
            }
        }        

        if($request->hasFile('featuredimage')){

            $posts->addMedia($request->featuredimage)
                    ->toMediaCollection('posts');

        }

        return redirect(route('posts.index'))->withMessage('post 😊 created successfully');
    }

    public function edit(Post $post)
    {
        $tags = Tag::get(['id','name']);

        $post->load('tags');

        Gate::authorize('update', $post);
            return view('cms.posts.edit',compact('tags','post'));
    }

    public function update(PostStoreRequest $request, Post $post)
    {
        // dd($request->input('featuredimage', false));
        $input = $request->validated();

        $postType = $request->postType; #check Post is draft or published

        switch ($postType) {
            case 'draft':
                $input['published'] = false;
                break;

            default:
                $input['published'] = true;
                break;
        }
        // dd(request('tags'));
        // $post->update($input);

        if (request('tags') != '') {
            $tags = explode(',', request('tags'));
            foreach ($tags as $tag_name) {
                $tag = Tag::updateOrCreate(['name' => $tag_name]);
                // dd($tag);
                $post->tags()->sync($tag);;
            }
        }

blade Now I don't want to use the dropdown only input box

<div class="form-group">
<label>Tags (comma-separted)</label>

<input type="text" name="tags" class="form-control" 
                                            value="{{ $post->tags_values }}"
                                    />
{{-- <input type="text" name="tags" class="form-control" 
value="@foreach ($tags as $tag){{ $post->tags->contains($tag->id) ? $tag->name : '' }}@endforeach"/> --}}

@error('tags')
<small class="form-text text-red">{{ $message }}</small>
@enderror
</div>
Oct
31
3 weeks ago
Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'id' Doesn't Have A Default Value (SQL: Insert Into `migrations` (`migration`, `batch`) Values (2020_10_31_043457_create_booking_activities_table, 7))

@nakov

ALTER TABLE migrations MODIFY id INTEGER NOT NULL AUTO_INCREMENT;

Where I have to run this command? under php my admin or under command line?

Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'id' Doesn't Have A Default Value (SQL: Insert Into `migrations` (`migration`, `batch`) Values (2020_10_31_043457_create_booking_activities_table, 7))

@nakov @globaltote Now I did first migrate:fresh after run the command php artisan migrate Now this sends error for other table:

Migrating: 2016_06_01_000001_create_oauth_auth_codes_table

   Illuminate\Database\QueryException

  SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into `migrations` (`migration`, `batch`) values (2016_06_01_000001_create_oauth_auth_codes_table, 1))

could you please tell me how can I solve this migration problem.

Activity icon

Replied to SQLSTATE[HY000]: General Error: 1364 Field 'id' Doesn't Have A Default Value (SQL: Insert Into `migrations` (`migration`, `batch`) Values (2020_10_31_043457_create_booking_activities_table, 7))

@nakov

here: https://stackoverflow.com/a/56766699/1457270

yes I checked this, But how to solve my php artisan migrate command because it sends error for all migration file.

should I've used ->autoIncrement()?

    public function up()
    {
        Schema::create('booking_activities', function (Blueprint $table) {
            $table->id()->autoIncrement();
            $table->string('title');
            $table->softDeletes();
            $table->timestamps();
        });
    }

Activity icon

Started a new Conversation SQLSTATE[HY000]: General Error: 1364 Field 'id' Doesn't Have A Default Value (SQL: Insert Into `migrations` (`migration`, `batch`) Values (2020_10_31_043457_create_booking_activities_table, 7))

Error:

  SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into `migrations` (`migration`, `batch`) values (2020_10_31_043457_create_booking_activities_table, 7))

Basically I've upgraded my project laravel 7.x to laravel8.x. And while running the command php artisan migrate it send me the errror. Can anyone tells me what I did wrong? ***This is my migration file code

<?php

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

class CreateBookingActivitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('booking_activities', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->softDeletes();
            $table->timestamps();
        });
    }

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

Oct
22
1 month ago
Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck okk I'll try this technique further letter.

$auth_profile->update(Arr::except($input, 'profile_photo_path'));

Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck Now I've changed my code and write own code. Deleted the copied code In User.php Model

   public function updateProfilePhoto($photo)
    {
        if($photo){
            // dd($this->profile_photo_path);
            $this->deletepreviousImage($this->profile_photo_path);

            $image = $photo->storePublicly('profile-photos',$this->profilePhotoDisk());

            $this->update(['profile_photo_path' => $image]);
        }
    }

    public function deletepreviousImage($previous)
    {
        Storage::disk($this->profilePhotoDisk())->delete($previous);
    }

	protected function profilePhotoDisk()
    {
        return isset($_ENV['VAPOR_ARTIFACT_NAME']) ? 's3' : 'public';
    }

And in the controller file, I have done some refactoring the code like this one

    public function update(UpdateProfileInfoRequest $request, User $auth_profile)
    {
        // $input = $request->validated();
        $input = $request->except(['profile_photo_path']);

        // dd($input);
        $auth_profile->update($input);

        $auth_profile->updateProfilePhoto($request->profile_photo_path);

        return redirect()->back()->withInfo('Profile updated succesfully');
    }
Activity icon

Replied to Laravel Basic Problem

@araw try to convert all path like this: {{ asset('your_path') }}

<link href="{{ asset('assets/vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
<script src="{{ asset('assets/js/main.js') }}"></script>

do for all like this

And also check view page resource all css loaded or not.

Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck In controller like this

  public function update(UpdateProfileInfoRequest $request, User $auth_profile)
    {
        $input = $request->validated();

        $photo = $request->profile_photo_path;

        // // dd($input);

        $auth_profile->update($input);

        if ($request->hasFile('profile_photo_path')) {

            $auth_profile->updateProfilePhoto($photo);
        }


        return redirect()->back()->withInfo('Profile updated succesfully');
    }

Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck No, I'm not using the jetstream. I'm using the laravel-ui and I copied the profile photo functionality from jetstream.

<?php

namespace App;

use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Support\Facades\Storage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable, HasRoles, SoftDeletes, HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'firstname',
        'lastname',
        'profile_photo_path',
        'mobile_number',
        'address',
        'description',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token', 'deleted_at',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
        'full_name',
        'single_role_name',
    ];

    /**
     * Update the user's profile photo.
     *
     * @param  \Illuminate\Http\UploadedFile  $photo
     * @return void
     */
    public function updateProfilePhoto(UploadedFile $photo)
    {
        tap($this->profile_photo_path, function ($previous) use ($photo) {
            $this->forceFill([
                'profile_photo_path' => $photo->storePublicly(
                    'profile-photos',
                    ['disk' => $this->profilePhotoDisk()]
                ),
            ])->save();
            dd($previous, $this->profilePhotoDisk());
            if ($previous) {
                // unlink($previous);
                Storage::disk($this->profilePhotoDisk())->delete($previous);
            }
        });
    }

    /**
     * Get the URL to the user's profile photo.
     *
     * @return string
     */
    public function getProfilePhotoUrlAttribute()
    {
        return $this->profile_photo_path
            ? Storage::disk($this->profilePhotoDisk())->url($this->profile_photo_path)
            : $this->defaultProfilePhotoUrl();
    }

    /**
     * Get the default profile photo URL if no profile photo has been uploaded.
     *
     * @return string
     */
    protected function defaultProfilePhotoUrl()
    {
        return 'https://ui-avatars.com/api/?name=' . urlencode($this->name) . '&color=7F9CF5&background=EBF4AA';
    }

    /**
     * Get the disk that profile photos should be stored on.
     *
     * @return string
     */
    protected function profilePhotoDisk()
    {
        return isset($_ENV['VAPOR_ARTIFACT_NAME']) ? 's3' : 'public';
    }

    public function getFullNameAttribute()
    {
        return (!empty($this->firstname && $this->lastname))
            ? "{$this->firstname} {$this->lastname}"
            : "{$this->name}";
    }

    protected static function boot()
    {
        parent::boot();

        static::created(function ($user) {
            # Here condition check if user is logged in and create a User model then assign role otherwise else condition
            if (Auth::check()) {
                $user->assignRole(2); # Role 2 Admin

            } else {
                $user->assignRole(3); # Role 3 User default registration

            }
        });
    }

}

Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck output is:

Illuminate\Http\UploadedFile {#1695 ▼
  -test: false
  -originalName: "freezeface.png"
  -mimeType: "image/png"
  -error: 0
  #hashName: "8Hv9V66kO3IhlopJKk8MZsjwhlmq8MNxg5bGTPl9"
  path: "C:\Users\Nick\AppData\Local\Temp"
  filename: "php7670.tmp"
  basename: "php7670.tmp"
  pathname: "C:\Users\Nick\AppData\Local\Temp\php7670.tmp"
  extension: "tmp"
  realPath: "C:\Users\Nick\AppData\Local\Temp\php7670.tmp"
  aTime: 2020-10-22 06:33:44
  mTime: 2020-10-22 06:33:44
  cTime: 2020-10-22 06:33:44
  inode: 19140298416685518
  size: 96275
  perms: 0100666
  owner: 0
  group: 0
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
  linkTarget: "C:\Users\Nick\AppData\Local\Temp\php7670.tmp"
}

"public"

Activity icon

Replied to Laravel8 Image Not Delete From Directory

@sinnbeck

Does the code inside the tap function get run ?

Yes, it is runs. But the problem I faced previous image in not deleted from directory.

I copied these method from laravel8 jetstream default image upload method

Activity icon

Started a new Conversation Laravel8 Image Not Delete From Directory

In my project image update successfully working but the problem I've found is that previous image is not deleted form the directory. can anyone tells me whats wrong with this code. THis is controller method

    public function update(UpdateProfileInfoRequest $request, User $auth_profile)
    {
        $input = $request->validated();

        $photo = $request->profile_photo_path;

        // dd($input);

        $auth_profile->update($input);

        if ($request->hasFile('profile_photo_path')) {

            $auth_profile->updateProfilePhoto($photo);
        }


        return redirect()->back()->withInfo('Profile updated succesfully');
    }

THis is Model function

   public function updateProfilePhoto(UploadedFile $photo)
    {
        tap($this->profile_photo_path, function ($previous) use ($photo) {
            $this->forceFill([
                'profile_photo_path' => $photo->storePublicly(
                    'profile-photos',
                    ['disk' => $this->profilePhotoDisk()]
                ),
            ])->save();

            if ($previous) {
                Storage::disk($this->profilePhotoDisk())->delete($previous);
            }
        });
    }
  protected function profilePhotoDisk()
    {
        return isset($_ENV['VAPOR_ARTIFACT_NAME']) ? 's3' : 'public';
    }
Oct
20
1 month ago
Activity icon

Started a new Conversation Call To Undefined Relationship [booking_service] On Model [App\BookingEvent].

Can anyone solve this problem What I wrong with these relationship? This is my BookingEvent Model

<?php

namespace App;

use Illuminate\Support\Str;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class BookingEvent extends Model
{
    use SoftDeletes, HasFactory, HasSlug;
    /**
     * @var string
    */
    protected $table = 'booking_events';

    /**
     * @var string
    */
    protected $primaryKey = 'id';


    /**
     * @var array
    */
    protected $fillable = [
        'event_name',
        'user_id',
        'booking_service_id',
        'duration',
        'price',
        'event_start',
        'event_end',
        'event_description',
    ];

    /**
     * Get the event based on the booking services.
     */
    public function bookingService()
    {
        return $this->belongsTo( BookingService::class );
    }

    public function user()
    {
        return $this->belongsTo( User::class );
    }


}

And this is my BookingService Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class BookingService extends Model
{
    use SoftDeletes, HasFactory;
    /**
     * @var string
    */
    protected $table = 'booking_services';

    /**
     * @var string
    */
    protected $primaryKey = 'id';

    /**
     * @var array
    */
    protected $fillable = ['service_name'];

    public function bookingevents() {

        return $this->hasMany( BookingEvent::class );

    }
}

and in index file

 @forelse($bookevents as $event)
                              <tr>
                                  <td>{{ $event->event_name ?? '' }}</td>
                                  <td>{{ $event->user->name ?? '' }}</td>
                                  <td>{{ $event->bookingService->service_name ?? '' }}</td>
@empty
.....................data...............
@endforelse
Activity icon

Replied to >>> Use App\{User,BookingEvent,BookingService} >>> BookingEvent::factory()->count(3)->for(BookingService::factory())->create(); PHP Error: Class 'Database/Factories/BookingEventFactory' Not Found In C:/laragon/www/acl/vendor/laravel/framework/src/Illumin

@sinnbeck After removing pkg and update the composer Now this kind of error occurs.

λ php artisan db:seed

   Illuminate\Contracts\Container\BindingResolutionException

  Target class [UserSeeder] does not exist.

IN my directory I have all seeder

database/seeders/UserSeeder

<?php

use App\User;
use Illuminate\Support\Str;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = User::factory()->times(3)->create();
    }
}
Activity icon

Replied to >>> Use App\{User,BookingEvent,BookingService} >>> BookingEvent::factory()->count(3)->for(BookingService::factory())->create(); PHP Error: Class 'Database/Factories/BookingEventFactory' Not Found In C:/laragon/www/acl/vendor/laravel/framework/src/Illumin

@sinnbeck

Why? You are using the new laravel 8 factory syntax?

THis project is upgraded from laravel 7 to laravel 8 and in previous I hae used the laravel 7 syntax.

SHould I have to remove this legacy pkg?

Activity icon

Replied to >>> Use App\{User,BookingEvent,BookingService} >>> BookingEvent::factory()->count(3)->for(BookingService::factory())->create(); PHP Error: Class 'Database/Factories/BookingEventFactory' Not Found In C:/laragon/www/acl/vendor/laravel/framework/src/Illumin

@divspace

Have you tried composer dump-autoload?

No.

@sinnbeck

Also make sure it is inside a directory database\Factories

It is inside database\Factories...

@divspace @sinnbeck basically I upgraded my project laravel7.x to laravel8.x. And in my project all models are inside of app not in models\model.php. And I installed the factory legacy pkg...

Oct
19
1 month ago
Activity icon

Replied to Laravel Got Stuck After Login. Laravel 5.8

@zayar @ssquare @andiliang @jonathanlilly @snapey It is the chrome extension problem.. disabled the all chrome extension or open chrome in new guest mode.. and try to run the project... Because I face the same issue..but resolved.. check this thread. https://laracasts.com/discuss/channels/laravel/419-page-expired-the-page-has-expired-due-to-inactivity-in-google-chrome?page=1#reply=654946

Activity icon

Replied to Login Page: 419 Page Expired In Google Chrome

@jlrdw @rodrigo.pedra Thank you very much I found it. It is an extension problem... I tried and open new guest chrome where there is no extension installed. And RUn the project and no issue occurs.

Note: Extension causes the issue..... Now I've to figure out which extension is responsible for this :)

Activity icon

Replied to Login Page: 419 Page Expired In Google Chrome

@jlrdw

did you figure out anything on this issue yet?

Still same issue...in chrome I checked my all authentication file and other but not works...

Some people on the discussions section on Laravel's Github repository are saying it can be related to installed extensions in Google Chrome.

@rodrigo.pedra Maybe It could be the problem of extension...because in my chrome browser I have installed lots of extensions.

Oct
18
1 month ago
Activity icon

Replied to Expected Status Code 200 But Received 500. Failed Asserting That 200 Is Identical To 500.

@sinnbeck @bugsysha I have seeder for permission and role. So could you please guide me how to test this?

    public function test_user_can_see_all_category()
    {
        $user = factory(User::class)->make();

        $role = Role::create(['name' => 'user']);
        $permission1 = Permission::create(['name' => 'category-list']);
        $role->givePermissionTo('category-list');

        $user->assignRole('user');

        $cat = Category::create(['name' => 'Dummy1']);

        $this->withoutExceptionHandling();

        $response = $this->actingAs($user)->get(route('category.index'));


        $response->assertStatus(200);
        $response->assertSee($cat->name);

    }
Activity icon

Replied to Expected Status Code 200 But Received 500. Failed Asserting That 200 Is Identical To 500.

@bugsysha if I used this

    public function test_user_can_see_all_category()
    {
        $user = factory(User::class)->make();

        $user->assignRole('superadmin');

        $cat = Category::create(['name' => 'Dummy1']);

        $this->withoutExceptionHandling();

        $response = $this->actingAs($user)->get(route('category.index'));


        $response->assertStatus(200);
        $response->assertSee($cat->name);

    }

it return me error like this


  There is no role named `superadmin`.

  at C:\laragon\www\acl\vendor\spatie\laravel-permission\src\Exceptions\RoleDoesNotExist.php:11
      7▕ class RoleDoesNotExist extends InvalidArgumentException
      8▕ {
      9▕     public static function named(string $roleName)
     10▕     {
  ➜  11▕         return new static("There is no role named `{$roleName}`.");
     12▕     }
     13▕
     14▕     public static function withId(int $roleId)
     15▕     {

  1   C:\laragon\www\acl\vendor\spatie\laravel-permission\src\Models\Role.php:89
      Spatie\Permission\Exceptions\RoleDoesNotExist::named("superadmin")

  2   C:\laragon\www\acl\vendor\spatie\laravel-permission\src\Traits\HasRoles.php:279
      Spatie\Permission\Models\Role::findByName("superadmin", "web")

and this my CategoryTest.php

<?php

namespace Tests\Feature;

use App\User;
use App\Category;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class CategoryTest extends TestCase
{
    use RefreshDatabase;

    public function setUp(): void
    {
        parent::setUp();

         // now re-register all the roles and permissions
        $this->app->make(\Spatie\Permission\PermissionRegistrar::class)->registerPermissions();

        // $this->withExceptionHandling();

    }

    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_user_can_see_all_category()
    {
        $user = factory(User::class)->make();

        $user->assignRole('superadmin');

        $cat = Category::create(['name' => 'Dummy1']);

        $this->withoutExceptionHandling();

        $response = $this->actingAs($user)->get(route('category.index'));


        $response->assertStatus(200);
        $response->assertSee($cat->name);

    }
}

Activity icon

Started a new Conversation Expected Status Code 200 But Received 500. Failed Asserting That 200 Is Identical To 500.

In my project I'm trying to write a test for category resource route. Wher auth middleware make a problem. In my project I have 3 roles superadmin, admin, user. Where superadmin has all permission. and admin or user has limited permission but at this time for user give only category crud operation.

can anyone tells me how to get rid of this problem?

  • Tests\Feature\CategoryTest > user can see all category
  Expected status code 200 but received 500.
  Failed asserting that 200 is identical to 500.

  at C:\laragon\www\acl\tests\Feature\CategoryTest.php:41
     37▕         $response = $this->actingAs($user)->get(route('category.index'));
     38▕
     39▕         $cat = Category::create(['name' => 'Dummy1']);
     40▕
  ➜  41▕         $response->assertStatus(200);
     42▕         $response->assertSee($cat->name);
     43▕
     44▕     }
     45▕ }

  1   C:\laragon\www\acl\vendor\phpunit\phpunit\phpunit:61
      PHPUnit\TextUI\Command::main()

and this is the test case

    public function test_user_can_see_all_category()
    {
        $user = factory(User::class)->make();

        // dd($user);

        $response = $this->actingAs($user)->get(route('category.index'));

        $cat = Category::create(['name' => 'Dummy1']);

        $response->assertStatus(200);
        $response->assertSee($cat->name);

    }

and the route is

 Route::group(['namespace' => 'Category'], function () {
            Route::resource('category', 'CategoryController');

            Route::resource('subcategory', 'SubCategoryController');
        });

This is the category controller

<?php

namespace App\Http\Controllers\Category;

use App\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class CategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('permission:category-list')->only('index');
        $this->middleware('permission:category-create')->only('create');
        $this->middleware('permission:category-view')->only('view');
        $this->middleware('permission:category-edit')->only('edit');
        $this->middleware('permission:category-delete')->only('destroy');
    }

    public function index()
    {
        $allCategory = Category::latest()->get();

        return view('cms.categories.index',compact('allCategory'));


    }


    public function create()
    {
        return view('cms.categories.create');
    }


    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|unique:categories|max:50',
        ]);

        Category::create($validatedData);

        return redirect(route('category.index'))->with('message','category created successfully');
    }


    public function show(Category $category)
    {
        return view('cms.categories.view',compact('category'));
    }


    public function edit(Category $category)
    {
        return view('cms.categories.edit',compact('category'));
    }

    public function update(Request $request, Category $category)
    {
        $validatedData = $request->validate([
            'name' => 'required|unique:categories|max:50',
        ]);

        $category->update($validatedData);

        return redirect(route('category.index'))->with('message','category updated successfully');
    }

    public function destroy(Category $category)
    {
        $category->delete();

        return redirect(route('category.index'))->with('message','category deleted successfully');
    }
}