Skip to main content

Posts

Showing posts from March, 2020

Eloquent Relationship Explained (MANY TO MANY) with attach,detach,sync

When you create a brand new project you have users table and User model already by default. So, now create another table with model: php artisan make:model Role -m This will create Role model as well as roles table. Now as it is many to many relation. So we need a pivot table. Pivot table naming convention: role_user Here role is written first as because alphabetically r comes before u. and laravel eloquent relationship takes in this way. So, you should remember this always. and use _ in between role and user. like: role_user So, let's create role_user table. php artisan make:migration create_role_user_table --create=role_user naming covention of pivot says that role_user table is singular. users table includes: id name, email pivot table role_user includes: user_id role_id roles table includes: id name migrate it all. Many to Many Relation: Go to User model and write: public function roles(){  r...

Eloquent Relationship Explained (ONE TO MANY)

Suppose you have two tables: users and posts tables. users table includes: id ,name,email posts table includes: id,title,body, user_id One to many relationship: Go to User model and write: public function posts(){  return $this->hasMany('App\Post'); } Look at the function naming convention. It's plural as it is one to many relationship. Store: $user->posts()->save($post); Here, $user variable comes from findorfail($id). and $post variable has taken the requested data from user. I haven't shown all of this in details here as it is only to understand how one to many relationship actually works. Show: foreach($user->posts as $post){    echo $post->title."<br>"; } Update: $user->posts()->where('id','=',2)->update(['title'=>'your updated title','body'=>'your updated body'); Delete: $user->posts->whereId(1)->delete(); To delete all t...

Eloquent Relationship Explained (ONE TO ONE)

One to one relationship: Suppose you have two tables users and addresses: Users table: id ,name,email Addresses table: id,name, user_id In the address table the user_id will come from the users table. Be careful about the naming convention. Your Model name is User so table name is users so to get id from users table to addresses table you have to write according to the model name in the field of address like user_id . So to declare one-to-one relationship: Just think that user can have only one address. So,  go to User model and write: public function address(){  return $this->hasOne('App\Address'); } here as this is one to one we are using singular function name which is address(). Store: $user->address()-> save($address); [Here, $user is finding the user by id, and $address is saving the requested address] Show: To show the address name $user->address->name; Update: $address = Address::whereUserId(1)->first(); $address...

Add [name] to fillable property to allow mass assignment on [App\Customer].

This mass assignment error occurs when you don't declare protected or guarded to your model. so, just write protected $fillable=[              'name', ]; or, protected $guarded=[]; both are same. $guarded is the opposite of $fillable but acts the same. but if you put name inside $guarded like: $guarded =['name'], than it will only guard this means it will not allow you to give data to name. so, living guarded blank is same as protected $fillable =['name'];

Simple laravel factory

UserFactory.php $factory -> define ( User :: class ,  function  ( Faker   $faker ) {      return  [          'name'  =>  $faker -> name ,          'email'  =>  $faker -> unique ()-> safeEmail ,          'email_verified_at'  =>  now (),          'password'  =>  '$2y$10$92IXUN...' ,  // password          'role_id'  =>  function (){              return  App\ Role :: all ()-> random ();         },          'remember_token'  =>  Str :: random ( 10 ),     ]; }); ...

Foreign key constraint is incorrectly formed (Laravel) reasons explained

If you ever faced this, which is obvious. Then you should remember there can be number of reasons for this to happen. To understand this: Suppose i have  two tables. roles and users. In you have a user table and there you have a foreign key called role_id which is indicating roles table. Reason Number 1: So when you run migration, laravel expects to have role table before user table. cause role_id is coming from role table. you can place your migration file of role by renaming the date. Reason Number 2: You can declare foreign key in many ways. interger, bigInteger, unsignedBigInteger. Don't forget to give the reference table name on the example:  -> references ( 'id' )-> on ( 'roles' )

Invalid argument supplied for foreach()

This can cause if the foreach loop is finding null values and trying to insert null value but fails. so to avoid this what we can do, we can check if the request is null or there is value inside the request which came to the controller. Example: Here we have used isset. you can use if else condition inside the foreach loop. $roles =  $request -> role_name ;          if ( isset ( $roles )){              foreach ( $roles  as  $role )             {                  ...             }         }

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails There are many reasons for this to happen. One of them is giving a wrong column name in your controller. For example: suppose you have given userrr_id instead of user_id. which is not available in your database.

Looking for an answer (Laravel)

Fatal error: Uncaught ReflectionException: Class App\Http\Kernel does not exist in C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Container\Container.php:729 Stack trace: #0 C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Container\Container.php(729): ReflectionClass->__construct('App\Http\Kernel') #1 C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Container\Container.php(608): Illuminate\Container\Container->build('App\Http\Kernel') #2 C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Container\Container.php(564): Illuminate\Container\Container->resolve('App\Http\Kernel', Array) #3 C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(709): Illuminate\Container\Container->makeWith('App\Http\Kernel', Array) 4 C:\laragon\www\BookTime\vendor\laravel\framework\src\Illuminate\Container\Container.php(248): Illuminate\Foundation\Application->make...

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists

While migration to db you often face/might face this error which says the table name that you wrote is already exists in the database. so in that case one of the solutions that you can try is wrapping up your create schema with this: if(!Schema::hasTable('users')){ } Example: if (! Schema :: hasTable ( 'users' )){              Schema :: create ( 'users' ,  function  ( Blueprint   $table ) {                  $table -> bigIncrements ( 'id' );                  $table -> bigInteger ( 'role_id' )-> unsigned ()-> nullable ();                  $table -> foreign ( ' role_id ' )-> references ( 'id' )-> on ( 'roles' ) ...

Mail setup in laravel's .env file (Mailtrap & Gmail)

//MAIL LARAVEL - MAILTRAP MAIL_DRIVER=smtp MAIL_HOST=smtp.mailtrap.io MAIL_PORT=2525 MAIL_USERNAME= (Get the mail username token from mailtrap website) MAIL_PASSWORD= (Get the mail password token from mailtrap website) MAIL_ENCRYPTION=null //MAIL LARAVEL - GMAIL  MAIL_DRIVER=smtp MAIL_HOST=smtp.googlemail.com MAIL_PORT=465 MAIL_USERNAME= ENTER_YOUR_EMAIL_ADDRESS(GMAIL) MAIL_PASSWORD= ENTER_YOUR_GMAIL_PASSWORD MAIL_ENCRYPTION=ssl

EMAIL CHECKING USING AJAX

$.ajax({     /* the route pointing to the post function */     url: '/api/mail-check',     type: 'POST',     /* send the csrf-token and the input to the controller */     data: {_token: CSRF_TOKEN, 'test' : 'tesst - data'},     dataType: 'JSON',     /* remind that 'data' is the response of the AjaxController */     success: function (data, res) {         console.log(data)     } }); var CSRF_TOKEN = $('meta[name="csrf-token"]').attr("content");             $.ajax({                 /* the route pointing to the post function */                 url: "/api/mail-check",                 type: "POST",                 /* send the csrf-token and the input to the controller */ ...

LARAVEL 7 (NEW FEATURES)

Laravel 7 released on 3rd March, 2020. Previous version of laravel is 6.  Laravel 7 is 2x faster in terms of cache and much more. Major release comes every 6 months in laravel. Bug fixes will come until 3rd September, 2020 and Security fixes will come untill 3rd March, 2021. Features: Laravel AirLock Custom Eloquent Casts Blade Component Tags Http Client Route Caching Speed Artisan Test command CORS Support String Operation Multiple Mail-Driver and much more.

Custom Middleware

1) php artisan make:middleware AuthorMiddleware 2) Go to author middleware and write:   public function handle($request, Closure $next)     {         // YOUR LOGIC TO HANDLE AUTHENTICATION. My Example:          $user = $request->user();         if($user->role_id === 1 || $user->role_id === 2){             return $next($request);         }         return redirect('/');     } 3) Now we need to register this is kernel.php like this: 'author' => \App\Http\Middleware\AuthorMiddleware::class, 4) Now go to your controller and write: public function __construct(){         $this->middleware('author',['only' => ['create','store','edit','update']]);         $this->middleware('admin',['only' => ['delete','trash','restore','permanentDelete']]);   ...

Getting error while dropping foreign key column in laravel

If  you get an error like this while running migrate refresh:  SQLSTATE[HY000]: General error: 1005 Can't create table `blogname`.`#sql-6b44_1f1` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `blogs` add constraint `blogs_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade) then go to your migration file and write the down() function like the following: public   function   up ()     {          Schema :: table ( 'blogs' ,  function  ( Blueprint   $table ) {              $table -> bigInteger ( 'user_id' )-> unsigned ()-> index ()-> nullable ();              $table -> foreign ( 'user_id' )-> references ( 'id' )-> on ( 'users' ) -> onDelete ( 'cascad...