0% found this document useful (0 votes)
87 views

PHP Laravel Course: 23 Laravel Model (Working With Database)

This document provides an overview of working with databases and models in Laravel. It discusses connecting to databases like MySQL, performing CRUD operations using the query builder and Eloquent ORM, and creating and using models. Examples are given for inserting, retrieving, updating and deleting records from a student database table using the DB facade and a Student model. The document also covers generating a model from the command line and using the model for CRUD operations as an alternative to the query builder.

Uploaded by

Myanmar Citizen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

PHP Laravel Course: 23 Laravel Model (Working With Database)

This document provides an overview of working with databases and models in Laravel. It discusses connecting to databases like MySQL, performing CRUD operations using the query builder and Eloquent ORM, and creating and using models. Examples are given for inserting, retrieving, updating and deleting records from a student database table using the DB facade and a Student model. The document also covers generating a model from the command line and using the model for CRUD operations as an alternative to the query builder.

Uploaded by

Myanmar Citizen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PHP Laravel Course

created by Wai Yan Aung

23 Laravel Model (Working with database)

Connecting to Database
Laravel has made processing with database very easy. Laravel currently supports
following 4 databases:
- MySQL
- Postgress
- SQLite
- SQL Server
The query to the database can be fired using raw SQL, the fluent query builder, and
the Eloquent ORM. To understand the all CRUD (Create, Read, Update, Delete)
operations with Laravel, we will use simple student management system. Configure
the database in config/database.php file and create the college database with
structure in MySQL as shown in the following table.

Database: College

Table: student

Column Name Column Datatype Extra

id Int(11) Primary Key | Auto


Increment

name varchar(25)

We will see how to add, delete, update and retrieve records from database using
Laravel in student table.
Insert Records
We can insert the record using the DB facade with insert method. The syntax of
insert method is as shown in the following table.

Syntax bool insert(string $query, array $bindings = array())

Parameters - $query(string) – query to execute in database


- $bindings(array) – values to bind with queries

Returns bool

Description Run an insert statement against the database.

Example

Step 1: Execute the below command to create a controller called


StudInsertController

php artisan make:controller StudentController –-resource

Step 2: Copy the following app/Http/Controllers/StudentController.php.

use DB;

public function create()


{
return view('student.create');
}

public function store(Request $request)


{
$name = $request->input('name');
DB::insert('insert into student (name) values(?)',[$name]);
echo "Record inserted successfully.<br/>";
echo '<a href="/student/create">Click Here</a> to go back.';
}
Step 3: Create a view file called resources/views/student/create.blade.php and copy
the following code in that file.

<html>
<head><title>Student Management | Add</title></head>
<body>
<form action="/student/store" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' value="Add student" /></td>
</tr>
</table>
</form>
</body>
</html>

Step 4: Add the following lines in routes/web.php.

Route::get('student/create',
array('as'=>'student/create','uses'=>'StudentController@create'));
Route::post('student/store',
array('as'=>'student/store','uses'=>'StudentController@store'));

Retrieve Records
We can insert the record using the DB facade with insert method. The syntax of
insert method is as shown in the following table.

Syntax array select(string $query, array $bindings = array())

Parameters -$query(string) – query to execute in database


- $bindings(array) – values to bind with queries

Returns array

Description Run a select statement against the database.


Example
We will use the previous StudentController again.
Step 1: Copy the following app/Http/Controllers/StudentController.php.

public function index()


{
$users = DB::select('select * from student');
//return view('student.index',['users'=>$users]);
return view('student.index')
->with('users', $users);
}

Step 2: Create a view file called resources/views/student/index.blade.php and copy


the following code in that file

<html>
<head><title>View Student Records</title></head>
<body>
<a href='/student/create'>New Student</a><br/>
<table border=1>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
</tr>
@endforeach
</table>
</body>
</html>
Step 3: Edit the “Store” method/action at StudentController

public function store(Request $request)


{
$name = $request->input('name');
DB::insert('insert into student (name) values(?)',[$name]);
//echo "Record inserted successfully.<br/>";
//echo '<a href="/student/create">Click Here</a> to go back.';
return redirect()->route('student');
}

Step 4: Add the following lines in routes/web.php.

Route::get('student',
array('as'=>'student','uses'=>'StudentController@index'));

Update Records
We can update the records using the DB facade with update method. The syntax of
update method is as shown in the following table.

Syntax int update(string $query, array $bindings = array())

Parameters - $query(string) – query to execute in database


- $bindings(array) – values to bind with queries

Returns int

Description Run an update statement against the database.

Example

We will use the previous StudentController again.


Step 1: Copy the following app/Http/Controllers/StudentController.php.

public function edit($id)


{
$users = DB::select('select * from student where id = ?',[$id]);
return view('student.edit',['users'=>$users]);
}
public function update(Request $request, $id)
{
$name = $request->input('stud_name');
DB::update('update student set name = ? where id = ?',[$name,$id]);
echo "Record updated successfully.<br/>";
echo '<a href="/student">Click Here</a> to go back.';
}

Step 2: Added the following code to index.blade.php [Bold letters]

<html>
<head><title>View Student Records</title></head>
<body>
<a href='student/create'>New Student</a><br/>
<table border=1>
<tr>
<td>ID</td>
<td>Name</td>
<td>Action</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href='student/edit/{{ $user->id }}'>Edit</a></td>
</tr>
@endforeach
</table>
</body>
</html>

Step 3: Create a new view file for edit page student/edit.blade.php.

<html>
<head><title>Student Management | Edit</title></head>
<body>
<form action="/student/update/<?php echo $users[0]->id; ?>" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='stud_name' value='<?php echo
$users[0]->name; ?>' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' value="Update student" /></td>
</tr>
</table>
</form>
</body>
</html>

Step 4: Add the following lines in routes/web.php.

Route::get('student/edit/{id}',
array('as'=>'student/edit','uses'=>'StudentController@edit'));
Route::post('student/update/{id}',
array('as'=>'student/update','uses'=>'StudentController@update'));

Delete Records
We can delete the record using the DB facade with the delete method. The syntax of
delete method is shown in the following table.

Syntax int delete(string $query, array $bindings = array())

Parameters - $query(string) – query to execute in database


- $bindings(array) – values to bind with queries

Returns int

Description Run a delete statement against the database.


Example

We will use the previous StudentController again.


Step 1: Copy the following app/Http/Controllers/StudentController.php.

public function destroy($id)


{
DB::delete('delete from student where id = ?',[$id]);
echo "Record deleted successfully.<br/>";
echo '<a href="/student">Click Here</a> to go back.';
}

Step 2: Added the following code to index.blade.php [Bold letters]

<html>
<head><title>View Student Records</title></head>
<body>
<a href='student/create'>New Student</a><br/>
<table border=1>
<tr>
<td>ID</td>
<td>Name</td>
<td>Action</td>
<td>Action</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href='student/edit/{{ $user->id }}'>Edit</a></td>
<td><a href='student/delete/{{ $user->id }}'>Delete</a></td>
</tr>
@endforeach
</table>
</body>
</html>
Step 3: Add the following lines in routes/web.php.

Route::get('student/delete/{id}',
array('as'=>'student/delete','uses'=>'StudentController@destroy'));

Models
To create a new model in laravel from artisan is and framework will create a new
model under app/ .

php artisan make:model student

After run the creating model command, framework will create one model class file
under app/student.php folder by the following

<?php

namespace laravel_5_3;

use Illuminate\Database\Eloquent\Model;

class student extends Model


{
protected $table = 'student';

protected $fillable = [
'id',
'name'
];
}

Read function with model


at index function of StudentController

use laravel_5_3\student as Student;


public function index()
{
//$users = DB::select('select * from student');
// Select All Student
$users = Student::all();
return view('student.index')
->with('users', $users);
}

Create function with model


at store function of StudentController

public function store(Request $request)


{
$name = $request->input('name');
//DB::insert('insert into student (name) values(?)',[$name]);

// Create / Insert new student


$student = new Student;
$student->name = "Testing Name";
$student->save();

echo "Record inserted successfully.<br/>";


echo '<a href="/student/create">Click Here</a> to go back.';
}

Edit function with model


at edit and update functions of StudentController

public function edit($id)


{
//$users = DB::select('select * from student where id = ?',[$id]);

// Select with conditions


$users = Student::where('id', $id)
->get();

return view('student.edit',['users'=>$users]);
}
public function update(Request $request, $id)
{
$name = $request->input('stud_name');
//DB::update('update student set name = ? where id = ?',[$name,$id]);

// Update existing student


$student = Student::find($id);
$student->name = $name;
$student->save();

echo "Record updated successfully.<br/>";


echo '<a href="/student">Click Here</a> to go back.';
}

Delete function with model


at destroy function of StudentController

public function destroy($id)


{
//DB::delete('delete from student where id = ?',[$id]);

// Delete Student
$student = Student::find(1);
$student->delete();
echo "Record deleted successfully.<br/>";
echo '<a href="/student">Click Here</a> to go back.';
}

You might also like