Saturday, 23 April 2016

Unknown

Model in Laravel - Create model and interact with table at easyLaravel

Since in last post we created a migration for Articles table,now lets create model so that we can insert ,update rows in table.
So now you have got an idea what is model.

Definition of Model in laravel :
Each database table has a corresponding "Model" which is used to interact with that table.

Lets create Model 'Article' for table 'articles' using artisan console:

Step 1 : Run a composer.

Step 2 : Add following code -
" php artisan make:model Article "
Note: Plural name of the class will be used as the table name unless another name is explicitly specified using protected $table property
Model named Article is created in 'app' directory and extends 'Illuminate\Database\Eloquent\Model'

Properties in Model :
$table - $table property is used to specify table name.

' protected $table = 'articles';  '.
$primaryKey - specify primary key for table
' protected $primaryKey= 'id';  '
Lets interact with table add some rows and find them using methods of query builder.

Using php artisan tinker console to add ,update and find records in tables of article model.

1.Insert new row into articles:
 Step1: Run Composer and add following command-
"php artisan tinker ",you will get-

Create object of article model using following command:
">$article=new App\Article ".

We get $article object so lets add values to columns of articles table-
>$article->title ='First Article'.
>$article->description='Lorem Ipsumad'.
>$article->save();

save()method saves the record and you can check the database.
Note: You still have access to $article object so that we can update the article and again save().
>$article->title='First Article of Me';
>$article->save().

2.Find a record using find() function
Step 1: Run Composer and add following command-
"php artisan tinker "
Step2: Create object of article model using following command:
">$article =App\Article::find(1) ".
find() method accepts single parameter which primary key of that table .here 1 is primary key and $article object contains record id=1.
Find() method in laravel to get row
Summary:
Now since you got an idea of model ,in the next tutorial we are going to learn interesting topics :

  • Views
  • Blade templates


Unknown

About Unknown -

Freelancer,Entrepreneur,Aesthetic bodybuilder.

    Knows :
  • Laravel Framework
  • Ionic Framework + Angular JS
  • Bootstrap
  • CSS
  • Jquery

Subscribe to this Blog via Email :