Neeraj1005

Neeraj1005

Member Since 1 Year Ago

Experience Points
29,890
Total
Experience

110 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
137
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 6
29,890 XP
Oct
22
3 hours ago
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
2 days 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
3 days 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
4 days 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');
    }
}

Activity icon

Replied to Could Not Find Driver (SQL: PRAGMA Foreign_keys = ON;)

@sinnbeck Now this error comes

 • Tests\Feature\CategoryTest > user can see all category
   Spatie\Permission\Exceptions\RoleDoesNotExist

  There is no role with id `3`.

test case

$user = factory(User::class)->create();

        $user->assignRole('superadmin');

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

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

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

Replied to Could Not Find Driver (SQL: PRAGMA Foreign_keys = ON;)

@sinnbeck Yes you're right... It would other solution...

could please solve this new problem also... after fix this Now I'm getting this problem now

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

route

#And I'm using the auth middleware
Route::group(['middleware' => ['verified','auth']], function () {
 Route::group(['namespace' => 'Category'], function () {
            Route::resource('category', 'CategoryController');

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

Replied to Could Not Find Driver (SQL: PRAGMA Foreign_keys = ON;)

@sinnbeck means...? what i have to do for this... should I have to install this..?

Activity icon

Started a new Conversation Could Not Find Driver (SQL: PRAGMA Foreign_keys = ON;)

In my project I'm trying to make test cases but it throw me some this kind of error. can anyone tells me whats the problem with this. Basically I'm using the system window10 and local environment laragon and for database phpmyadmin running.

 • Tests\Feature\CategoryTest > user can see all category
   Illuminate\Database\QueryException

  could not find driver (SQL: PRAGMA foreign_keys = ON;)

This is my test case

 public function test_user_can_see_all_category()
    {
        $response = $this->get(route('category.index'));

        $response->assertStatus(200);
    }

and this is my phpunit.xml file

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
>
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <server name="APP_ENV" value="testing"/>
        <server name="BCRYPT_ROUNDS" value="4"/>
        <server name="CACHE_DRIVER" value="array"/>
        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>
        <server name="MAIL_MAILER" value="array"/>
        <server name="QUEUE_CONNECTION" value="sync"/>
        <server name="SESSION_DRIVER" value="array"/>
        <server name="TELESCOPE_ENABLED" value="false"/>
    </php>
</phpunit>
Oct
17
5 days ago
Activity icon

Replied to Login Page: 419 Page Expired In Google Chrome

@michaloravec now login is not working. Only page refreshed if I put the credentials and hit the login button only page is refreshed

Activity icon

Replied to Login Page: 419 Page Expired In Google Chrome

@michaloravec

   /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
    |--------------------------------------------------------------------------
    |
    | This option determines how your cookies behave when cross-site requests
    | take place, and can be used to mitigate CSRF attacks. By default, we
    | will set this value to "lax" since this is a secure default value.
    |
    | Supported: "lax", "strict", "none", null
    |
    */

    'same_site' => 'lax',

nothing is changed.. in same_site. I do not understand why it take too much time in chrome. In other browser login system works properly... Basically for authentication, I'm using the laravel-ui

Activity icon

Started a new Conversation Login Page: 419 Page Expired In Google Chrome

In my Laravel8.x project, I'm facing an issue. can anyone tells me what is happing basically and what should I have to do?

Basically, If I run my project in Google chrome and try to log in it takes too much time and sends me a page expire 419 error. But If I run my project in *Mozilla or Microsoft Edges browser the login system run smoothly no error page occurs. I'm confused about what is going on and what I did wrong.

Oct
14
1 week ago
Activity icon

Replied to Call To A Member Function GetClientOriginalName() On Null

@nikhillvl did you try dd()? And did you added the enctype="multipart/form-data" in you form tag

Activity icon

Started a new Conversation PHP Error: Class 'Database/Factories/BookingEventFactory' Not Found In C:/laragon/www/acl/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Factories/Factory.php

In my terminal using running the tinker cli. It send me this type of error. Can someone plz tell me what i did wrong. I am using the laravel 8.9.0 version.

Note: Basically I've upgraded my project form laravel 7 to laravel 8 and I've installed the legacy pkg for factroy.

λ php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.8 — cli) by Justin Hileman
>>> 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/Illuminate/Database/Eloquent/Factories/Factory.php on line 656

This is my BookingEventFactory

<?php

namespace Database\Factories;

use App\BookingEvent;
use App\BookingService;
use Illuminate\Database\Eloquent\Factories\Factory;

class BookingEventFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = BookingEvent::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'event_name' => $this->faker->name,
            'user_id' => 2,
            'booking_service_id' => BookingService::factory(),
            'duration' => '1 Hours',
            'price' => '1000',
            'event_description' => $this->faker->paragraph,
        ];
    }
}

Activity icon

Started a new Conversation >>> 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

In my laravel project having version 8.9.0. I'm trying to run factory command but this show this kind of error in tinker terminal

λ php artisan tinker
Psy Shell v0.10.4 (PHP 7.4.8 — cli) by Justin Hileman
>>> 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/Illuminate/Database/Eloquent/Factories/Factory.php on line 656

can anyone tells me what I did wrong. THis is my factory class method BookingEventFactory

<?php

namespace Database\Factories;

use App\BookingEvent;
use App\BookingService;
use Illuminate\Database\Eloquent\Factories\Factory;

class BookingEventFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = BookingEvent::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'event_name' => $this->faker->name,
            'user_id' => 2,
            'booking_service_id' => BookingService::factory(),
            'duration' => '1 Hours',
            'price' => '1000',
            'event_description' => $this->faker->paragraph,
        ];
    }
}

Oct
13
1 week ago
Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck thank you for help its working now using this =>JsonResource::withoutWrapping();

Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck is there any technique to change the formate of resource return data?

Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck instead resource collection If i used this it return the data like this:

0:	
id	3
event_name	"admin event"
user_id	2
booking_service_id	2
duration	"2 Hours"
price	"20"
event_description	"test"
event_start	"2020-10-13 13:41:45"
event_end	null
created_at	"2020-10-08T11:34:28.000000Z"
updated_at	"2020-10-08T11:34:28.000000Z"
deleted_at	null
bookingcustomers_count	1
short_description	"test"
booking_service	{…}
bookingcustomers	[…]
1:
id : data...........

2:
id: data etc.......
Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck it returns data in this format

data	
0	
id	3
title	"admin event"
start	"2020-10-08T11:34:28.000000Z"
1	
id	2
title	"Hair cutting"
start	"2020-10-08T11:31:19.000000Z"
2	
id	1
title	"business marketing"
start	"2020-10-08T10:48:54.000000Z"
Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck

Try opening the link in the browser manually to see if you get data

Yes it returns the data. But in fullcaledar script it not return any data.

      events: {
          url: '/bookingeventdata',
          type: 'GET',
          color: 'yellow',   // a non-ajax option
          textColor: 'black' // a non-ajax option
    },
Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck Is there any difference between them?

 return response()->json($event, 200); // But if i used this it returns 
		vs 
return new BookingEventResource($event); // If I used this is return nothing incalendar

Basically for listing the data in fullcalendar I need these field

  evetns: {
      title: 'my event',
      start: '2018-09-01'
    }

and I have data like this in my model

 protected $fillable = [
        'event_name',
        'user_id',
        'booking_service_id',
        'duration',
        'price',
        'event_start',
        'event_end',
        'event_description',
    ];

so basically for converting the event_name into title i've used the resource collection method. But it not returning any data in fullcalendar.

Activity icon

Replied to Exception Property [id] Does Not Exist On This Collection Instance.

@sinnbeck it's working. could you please solve this problem also.. Basically I'm using fullcalendar.io for calendar. But in script file it does not return any data. script

// Full calendar
document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var calendar = new Calendar(calendarEl, {
      plugins: [ dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin ],
      initialView: 'dayGridMonth',
      themeSystem: 'bootstrap',
      selectable:true,
      editable:true,
      headerToolbar: {
        left: 'today,prev,next',
        center: 'title',
        right: 'dayGridMonth,timeGridWeek,timeGridDay'
      },
      events: {
          url: '/bookingeventdata', //This is the url
          type: 'GET',
          color: 'yellow',   // a non-ajax option
          textColor: 'black' // a non-ajax option
    },
    });

    calendar.render();
});

if I using this method it return

public function calendarlist()
    {
         $event = BookingEvent::latest()->get();
         return response()->json($event, 200); // But if i used this it returns 
        //return new BookingEventResource($event); // If I used this is return nothing incalendar

    }

@sinnbeck could plz tell me whats the problem?

Activity icon

Started a new Conversation Exception Property [id] Does Not Exist On This Collection Instance.

In my laravel project in Fullcalendar.io I'm trying to list all the events using resource collection but I don't know why this through an error. did I make something wrong plz check below codes: Routes

Route::get('bookingeventdata', '[email protected]');

controller

public function calendarlist()
    {
        // $event = BookingEvent::latest()->get();
        // return response()->json($event, 200);
        return new BookingEventResource(BookingEvent::all());

    }

BookingEventResource

   public function toArray($request)
    {
        // return parent::toArray($request);
        return [
            'id' => $this->id,
            'event_name' => $this->event_name,
        ];
    }
Oct
06
2 weeks ago
Activity icon

Replied to BadMethodCallException Call To Undefined Method App\BookingService::bookevents()

@sergiu17 yes in route i have a bookevent route like this.

Route::resource('bookevents', 'BookingEventController');
Route::get('bookings/{bookservice:service_name}/event/{bookevent:event_name}','[email protected]')->name('event.create');

what should be order for this? should I have the routes?

Activity icon

Started a new Conversation BadMethodCallException Call To Undefined Method App\BookingService::bookevents()

can anyone tells me where did I make a mistakes. I tried but it gives me an error.

this is my route

Route::get('bookings/{bookservice:service_name}/event/{bookevent:event_name}','[email protected]')->name('event.create');

this is my method

public function create(BookingService $bookservice , BookingEvent $bookevent)
    {
        // $events = BookingEvent::get();
        // dd($events->id);
        // if (request('bookevent')) {
        //     $events = BookingEvent::get();
        //     dd($events->event_name);
        // }
        return view('bookings.booking_form', compact('bookservice', 'bookevent'));
    }

this is model1

<?php

namespace App;

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

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

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

    protected $appends = [
        'name',
    ];

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

    public function booking_events() {
        return $this->hasMany( BookingEvent::class );
    }

    public function getNameAttribute() {

        return lcfirst($this->service_name);
     }
}

this is model2

<?php

namespace App;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

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

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

    protected $with = ['booking_service'];

    // protected $withCount = ['booking_service'];

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

    protected $appends = [
        'short_description',
    ];
    /**
     * Get the event based on the booking services.
     */
    public function booking_service()
    {
        return $this->belongsTo( BookingService::class );
    }

    public function getDurationAttribute($value)
    {
        return $value . " Hours";
    }

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

    public function getShortDescriptionAttribute()
    {
        return Str::limit($this->event_description, 56, '...');
    }

    public function booking_customers()
    {
        return $this->belongsToMany( BookingCustomer::class );
    }
}

Sep
18
1 month ago
Activity icon

Replied to Which Package Development Course Is Good For Laravel?

@automica These are also paid in this Laracast. And I haven't take Laracast subscription yet

https://laracasts.com/series/building-laracasts/episodes/3

I will check this package also.

https://github.com/Jeroen-G/laravel-packager

Activity icon

Started a new Conversation Which Package Development Course Is Good For Laravel?

Hello, Laravel devs! I need your suggestion, basically, I searched/google a course for Laravel package development and I found a two paid course. Those are:

Can anyone suggest which would be good for starting and should I buy. Basically both creator are awesome. Now it is hard select which one....

Purchasing two courses is not possible.

Sep
14
1 month ago
Activity icon

Awarded Best Reply on Target Class [CarrierController] Does Not Exist.

@eliasniyonsaba If you are using Laravel8 do this.

To App/Providers/RouteServiceProvider.php add $namespace

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Controllers';
}

and this

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::middleware('web')
            ->namespace($this->namespace) // add this line
            ->group(base_path('routes/web.php'));

        Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace) // and this line
            ->group(base_path('routes/api.php'));
    });
}
Sep
11
1 month ago
Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@lara_garbage

'name' => Rule::unique('users')->ignore(auth()->id()),

Using this it send an error. But the main problem was id we just have to figureout this method $this->id

Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@lara_garbage @sarwarahmed

problem solved.

Both method are working $this->auth_profile->id instead of this $this->id. Basically here auth_profile is the wildcard name of your route or the wildcard variable you have used in your method.

Routes are

 Route::resource('auth_profile', 'UserProfileController');

# so wildcard route would be auth_profile/{auth_profile}

Request file

 'name' => [
                 'required',
                Rule::unique('users')->ignore(Auth::user()->id),
             ],

# OR
'name' => 'required|unique:users,name,'.$this->auth_profile->id,

in controller update method

public function update(UpdateProfileInfoRequest $request, User $auth_profile){
	// your statement
}
Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@lara_garbage Not working

 'name' => [
              'required',
            Rule::unique('users')->ignore($this->id),
            ],
Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@lara_garbage right what? I think it is right but the name field for updating causes problem

    public function rules()
    {
        return [
            'name' => 'required|name|unique:users,name,'.$this->id,
            'firstname' => 'required|max:75',
            'lastname' => 'required|max:75',
            //'email' => 'required|email|unique:users,email,'.$this->id
            'mobile_number' => 'string|size:10',
            'address' => 'string|max:255',
            'description' => 'string',
            'profile_photo_path' => 'image|mimes:jpeg,bmp,svg,jpg,png|max:512',
        ];
    }
Activity icon

Replied to How To Storage Upload An Image And Save In Database?

@oxbir Try this and let me know

    if ($request->hasFile('image')) {
	$originalname = $request->image->getClientOriginalName();

        $extension = $request->image->extension();

        $uploadpath = $request->image->storeAs('images/categories', $originalname, 'public');
    }
Category::create([
        'name' => $request->name,
        'latin' => $request->latin,
        'parent_id' => $request->parent_id,
        'image' => $originalname,
    ]);
    return redirect()->route('categories.index');
Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@lara_garbage

yea right there is no name validation rule

how to solve this? do you have any idea?

Activity icon

Replied to BadMethodCallException Method Illuminate\Validation\Validator::validateName Does Not Exist.

@sarwarahmed the validation error is returned in this case

The name has already been taken.