Laravel Tutorials
- What is laravel
- Laravel Installation
- Directory Structure
- htaccess
- Remove public from url
- Artisan Command
- Laravel Configuration
- Routing Configuration
- Namespaces
- Request
- Response
- Controller
- Model
- User Authentication
- Multi User Authentication
- Database Seeding
- Database
- Database Query
- ORM
- One-to-One Relationship
- One-to-Many Relationship
- Many to Many Eloquent Relationship
- Has One Through
- Has Many Through
- Querying Relations
- Middleware
- Laravel Views
- Blade Views
- Print data on view page
- Get Site URL
- Get URL Segment
- Get images from Storage folder
- Clear cache
- Form Class not found
- Flash Message in laravel
- Redirections
- path
- CRUD Projerct
- CRUD in Laravel
- CRUD progran
- Laravel Validation
- Jquery Validation
- Cookie
- Session
- Email Send in laravel
- File uploading
- CSRF Protection
- Helper in Laravel
- Helper Functions
- Guzzle Http Client
- Paypal Payment Gatway Integration
- Cron Job in laravel
- Flash message
- path
- Errors Handling
- Date Format
- Date Format Validation
- Display Image on View Page
- Update User Status using toggle button
- Delete Multiple Records using Checkbox in Laravel?
- Confirmation Before Delete Record
- Delete image from storage
- Remove/Trim Empty & Whitespace From Input Requests
- Block IP Addresses from Accessing Website
- How to Disable New User Registration in Laravel
- Redirect HTTP To HTTPS Using Laravel Middleware
- CKEditor
- slug generate unique
- Prevent Browser's Back Button After Logout
- Datatable dunamically
- encrypt & Decript
- Download File
- Rest API
- Shopping Cart
- Shopping Cart Example
- Dynamic Category-Subcategory Menu
- Ajax Search
- Interview Question
- laravel Tutorilal link
- laravel Tutorilal
Important Links
Eloquent ORM in laravel?
ORM
Object Relational Mapper (ORM).
Models typically live in the app/models directory, but you are free to place them anywhere that can be auto-loaded according to your composer.json file
ORM provides easy way to communicate with a database.
Defining Eloquent models
File name : index.php
php artisan make:model Student
Student model is used to retrieve and store information from our students database table.
<?php
namespace App;
use IlluminateDatabaseEloquentModel;
class Student extends Model
{
protected $fillable = array('first_name', 'last_name', 'email');
}
Each database table has a corresponding model that is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.
seeding is inserting records into our database.
Migration :-
After creating a model then create database migration, you can either use the –migration or -m option:
File name : index.php
php artisan make:model Student --migration
php artisan make:model Student -m
Seeders :-
File name : index.php
php artisan make:seeder StudentsRecordSeeder
<?php
use IlluminateDatabaseSeeder;
class StudentsRecordSeeder extends Seeder
{
public function run()
{
//
}
}
CRUD with Eloquent :-
Save Record in table.
$user_obj = new User();
$user_obj->name = "sana";
$user_obj->father_name = "mahtab";
$user_obj->dob = "07/05/2020";
$user_obj->address = "Dhandiha";
$user_obj->save();
########### OR ########
$userinfo = array(
'name' = > "sana",
'father_name' => "mahtab",
'dob' => "07/05/2020",
'address' => "Dhandiha",
);
$user_obj = new User();
$user_obj->save($userinfo);
Creating records :-
::create method to insert a new record in the database table.
User::create(array(
'first_name' => 'itech',
'last_name' => 'xpert',
'student_rank' => 1
));
############# OR #########
$userinfo = array(
'name' = > "sana",
'father_name' => "mahtab",
'dob' => "07/05/2020",
'address' => "Dhandiha",
);
User::create($userinfo);
############# OR #########
$userinfo = [
'name' = > "sana",
'father_name' => "mahtab",
'dob' => "07/05/2020",
'address' => "Dhandiha",
];
User::create($userinfo);
// Create a new user in the database...
$user = User::create(array('name' => 'mahtab'));
// here User is the model name.
// Retrieve the user by the attributes, or create it if it doesn't exist...
$user = User::firstOrCreate(array('name' => 'mahtab'));
// Retrieve the user by the attributes, or instantiate a new instance...
$user = User::firstOrNew(array('name' => 'mahtab'));
create method create a new object and assign different attributes to it. afterthat you can call the save() function and execute the code.
Methods such as firstOrCreate() or firstOrNew() are other options for creating records. These will enable finding a student with certain attributes; if that student is not found, then you will either create it in the database or instantiate a new instance.
Retrieving records from database table:-
Using Eloquent ORM, getting and finding records from the database.
you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also the find() method can be used with an array of primary keys, which will return a collection of matching records.
File name : index.php
$stud = Student::all();
// here Student is the model name.
it return all student list from students table.
################# OR #############
$userinfo = User::all();
$userinfo = User::get();
Retrieving A Record By Primary Key
$user = User::find(1);
var_dump($user->name);
Retrieving A Model By Primary Key Or Throw An Exception
Sometimes you may wish to throw an exception if a model is not found, allowing you to catch the exceptions using an App::error handler and display a 404 page.
$stud = student::findOrFail(1);
$stud = student::where('votes', '>', 50)->firstOrFail();
Querying Using Eloquent Models
$stud = Student::where('votes', '>', 50)->take(10)->get();
foreach ($stud as $user)
{
var_dump($user->name);
}
$stud = Student::where('name', '=', 'NB')->first();
$stud = Student::where('student_rank', '>', 5)->get();
$stud = Student::where('votes', '>', 100)->count();
Mass Assignment
When creating a new model, you pass an array of attributes to the model constructor. These attributes are then assigned to the model via mass-assignment.
all Eloquent models protect against mass-assignment by default.
To get started, set the fillable or guarded properties on your model.
Defining Fillable Attributes On A Model
The fillable property specifies which attributes should be mass-assignable. This can be set at the class or instance level.
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Defining Guarded Attributes On A Model
The inverse of fillable is guarded, and serves as a "black-list" instead of a "white-list"
class User extends Eloquent {
protected $guarded = array('id', 'password');
}
Note: When using guarded, you should still never pass Input::get() or any raw array of user controlled input into a save or update method, as any column that is not guarded may be updated.
Blocking All Attributes From Mass Assignment
the id and password attributes may not be mass assigned. All other attributes will be mass assignable. You may also block all attributes from mass assignment using the guard property:
protected $guarded = array('*');
Insert data :-
To create a new record in the database from a model, simply create a new model instance and call the save method.
File name : index.php
$obj = new User;
$obj->name = 'NB';
$obj->save();
$category_name = "Mobiel";
$category_slug = "Redmi-mobile";
$obj = New Category();
$obj->category_name = $category_name;
$obj->category_slug = $category_slug;
$obj->created_at = date('Y-m-d h:i:s');
$obj->save();
Updating A Retrieved Model :-
To update a model, you may retrieve it, change an attribute, and use the save method:
$obj = User::find(1);
$obj->email = 'mahtab.habib@gmail.com';
$obj->save();
Saving A Model And Relationships
Sometimes you may wish to save not only a model, but also all of its relationships. To do so, you may use the push method:
$user->push();
You may also run updates as queries against a set of models:
$affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));
Deleting An Existing Model
To delete a model, simply call the delete method on the instance:
$user = User::find(1);
$user->delete();
################# OR ############
User::where('id',2)->delete();
Deleting An Existing Model By Key
To delete a record and multiple records.
User::destroy(1);
User::destroy(array(1, 2, 3));
User::destroy(1, 2, 3);
you may also run a delete query on a set of models:
$affectedRows = User::where('votes', '>', 50)->delete();
To find and delete all students with rank level that is greater than 10.
Students::where('student_rank', '>', 10)->delete();
Update
User::where('id',3)->update(['name' => 'sana']);
Updating Only The Model's Timestamps
If you wish to simply update the timestamps on a model, you may use the touch method:
$user->touch();
Timestamps
By default, Eloquent will maintain the created_at and updated_at columns on your database table automatically. Simply add these timestamp columns to your table and Eloquent will take care of the rest. If you do not wish for Eloquent to maintain these columns, add the following property to your model:
Disabling Auto Timestamps
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
}
Query Scopes
Defining A Query Scope
Scopes allow you to easily re-use query logic in your models. To define a scope, simply prefix a model method with scope:
class User extends Eloquent {
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
public function scopeWomen($query)
{
return $query->whereGender('W');
}
}
File name : index.php
Relationships
Defining A One To One Relation
A one-to-one relationship is a very basic relation. For example, a User model might be associated with one Phone. To define this relationship, we place a phone method on the User model. The phone method should call the hasOne method and return its result:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
The first argument passed to the hasOne method is the name of the related model. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
$phone = User::find(1)->phone;
The SQL performed by this statement will be as follows:
select * from users where id = 1
select * from phones where user_id = 1
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. you may pass a second argument to the hasOne method:
return $this->hasOne('App\Phone', 'foreign_key');
Defining The Inverse Of The Relationship
we can access the Phone model from our User. Now, let's define a relationship on the Phone model that will let us access the User that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
Eloquent will try to match the user_id from the Phone model to an id on the User model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:
File name : index.php
public function user()
{
return $this->belongsTo('App\User', 'foreign_key');
}
File name : app/User.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php
File name : index.php