Celebrating 10 years in web hosting [email protected]

Simple Laravel CRUD with Resource Controllers

How to set up a simple Laravel CRUD with Resources Controllers? Creating, reading, updating, and deleting resources is used in a lot of every application.

How to setup a simple CRUD

Laravel helps to do the process easily using resource controllers.

Resource Controllers can make life easier and takes advantage of some cool Laravel routing techniques.

Today, we’ll go by the steps essential to get a fully functioning CRUD application using Laravel resource controllers.

For this article, we will go by the steps of having an admin panel to create, read, update, and delete (CRUD) a resource.

Let’s we can use csworks as our example. Also, we will use Eloquent ORM.

IF you want then buy a good, reliable, secure WordPress web hosting service  from here: click here

How to setup a simple CRUD

In this article we will show some steps:
  • First, Setting up the database and models
  • Secondly, Creating the resource controller and its routes
  • Thirdly, Creating the necessary views
  • Fourthly Explain each method in a resource controller

So get started, we will need the routes, the controller, and the view files.

Preparing our Database Ready

How to set up a simple Laravel CRUD with Resources Controllers?

Cswork Migration

At first, we need to set up a quick database so we can do all of our CRUD functionality.

So now, In the command line in the root directory of our Laravel application, let’s create a migration.

php artisan make:migration create_csworkss_table –table=csworks –create

This will create our cswork migration into app/database/migrations.

Now, open up that file, and let’s add a name, email, and cswork_level fields.

<?php

use IlluminateDatabaseSchemaBlueprint;

use IlluminateDatabaseMigrationsMigration;

class CreatecsworksTable extends Migration {

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create(‘csworks’, function(Blueprint $table)

{

$table->increments(‘id’);

$table->string(‘name’, 255);

$table->string(’email’, 255);

$table->integer(‘cswork_level’);

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::drop(‘csworks’);

}

}

And now from the command line again, we need let’s run this migration.

Make sure our database settings are good in app/config/database.php

And then run: php artisan migrate

Now our database has a csworks table to house all of the csworks we CRUD which means create, read, update, and delete.

If you can read more about migrations then you can check these links Laravel docs.

How to set up a simple Laravel CRUD with Resources Controllers?

You can purchase your hosting from Cloudsurph.comCloudsurph hosting is more reliable and comfortable for your business website and it is most secure.

Simple-Laravel-CRUD-with-Resource-Controllers

Eloquent Model for the csworks

So we have our database, and let’s create a simple Eloquent model.

So that we can easily access the csworks in our database.

You can read more about Eloquent ORM and you can see how you can use it in your self-applications.

Now, In the app/models folder, let’s create a cswork.php model.

<?php

class cswork extends Eloquent

{

}

That’s it for now!

Now, Eloquent can handle the rest.

So, by default, this model will link to our csworks table and we can access it later for our controllers.

Creating the Controller

Check the official Laravel docs, on resource controllers, you can create or generate a resource controller using the artisan tool.

And, let’s go ahead and do that. This is the easy part from the command line in the root directory of your self Laravel project, type: php artisan make:controller csworkController –resource

It will create our resource controller with all the methods that we need.

<?php

class csworkController extends BaseController {

/**

* Display a listing of the resource.

*

* @return Response

*/

public function index()

{

//

}

/**

* Show the form for creating a new resource.

*

* @return Response

*/

public function create()

{

//

}

/**

* Store a newly created resource in storage.

*

* @return Response

*/

public function store()

{

//

}

/**

* Display the specified resource.

*

* @param int $id

* @return Response

*/

public function show($id)

{

//

}

/**

* Show the form for editing the specified resource.

*

* @param int $id

* @return Response

*/

public function edit($id)

{

//

}

/**

* Update the specified resource in storage.

*

* @param int $id

* @return Response

*/

public function update($id)

{

//

}

/**

* Remove the specified resource from storage.

*

* @param int $id

* @return Response

*/

public function destroy($id)

{

//

}

}

Setting Up our Routes

We have generated our controller, now let’s make sure our application has the routes essential to use it.

So, this is the other easy part for your routes.php file, and add this line:

<?php

Route::resource(‘csworks’, ‘csworkController’);

And this will automatically assign more actions to that resource controller.

Now if you need to go to your browser and view your self-application at example.com/csworks, it will correspond to the proper method in your csworkController.

The Views

Since we have only four of our routes GET routes.

And we only need four views, in our app/views folder, so let’s make those views now.

app

└───views

└───csworks

│-index.blade.php

│-create.blade.php

│ -show.blade.php

│ -edit.blade.php

Making It for All Work Together

Now we have our database, migrations, and models.

Our controller and routes, and our views.

So let’s make all these things work together and build our application.

Now, we are going to go through the methods created in the resource controller one by one and make sure it all works.

Controller Function index()

Since in this function, we will get all the csworks and pass them to the view.

<?php

/**

* Display a listing of the resource.

*

* @return Response

*/

public function index()

{

// get all the csworks

$csworks = cswork::all();

// load the view and pass the csworks

return View::make(‘csworks.index’)

->with(‘csworks’, $csworks);

}

The View app/views/csworks/index.blade.php

Now let’s we create our view to loop for over the csworks and display them into a table.

How to set up a simple Laravel CRUD with Resources Controllers?

And we like using Twitter Bootstrap for our applications, so that the table will be use those classes.

<!DOCTYPE html>

<html>

<head>

<title>Cswork App</title>

<link rel=”stylesheet” href=”//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css”>

</head>

<body>

<div class=”container”>

<nav class=”navbar navbar-inverse”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”{{ URL::to(‘csworks’) }}”>cswork Alert</a>

</div>

<ul class=”nav navbar-nav”>

<li><a href=”{{ URL::to(‘csworks’) }}”>View All csworks</a></li>

<li><a href=”{{ URL::to(‘csworks/create’) }}”>Create a cswork</a>

</ul>

</nav>

<h1>All the csworks</h1>

<!– will be used to show any messages –>

@if (Session::has(‘message’))

<div class=”alert alert-info”>{{ Session::get(‘message’) }}</div>

@endif

<table class=”table table-striped table-bordered”>

<thead>

<tr>

<td>ID</td>

<td>Name</td>

<td>Email</td>

<td>cswork Level</td>

<td>Actions</td>

</tr>

</thead>

<tbody>

@foreach($csworks as $key => $value)

<tr>

<td>{{ $value->id }}</td>

<td>{{ $value->name }}</td>

<td>{{ $value->email }}</td>

<td>{{ $value->cswork_level }}</td>

<!– we will also add show, edit, and delete buttons –>

<td>

<!– delete the cswork (uses the destroy method DESTROY /csworks/{id} –>

<!– we will add this later since its a little more complicated than the other two buttons –>

<!– show the cswork (uses the show method found at GET /csworks/{id} –>

<a class=”btn btn-small btn-success” href=”{{ URL::to(‘csworks/’ . $value->id) }}”>Show this cswork</a>

<!– edit this cswork (uses the edit method found at GET /csworks/{id}/edit –>

<a class=”btn btn-small btn-info” href=”{{ URL::to(‘csworks/’ . $value->id . ‘/edit’) }}”>Edit this cswork</a>

</td>

</tr>

@endforeach

</tbody>

</table>

</div>

</body>

</html>

Now create a New Resource csworks.create

Controller Function create()

So, in this function, we will show how to the form for creating a new cswork.

This form will be to the process by the store() method.

<?php

/**

* Show the form for creating a new resource.

*

* @return Response

*/

public function create()

{

// load the create form (app/views/csworks/create.blade.php)

return View::make(‘csworks.create’);

}

How to set up a simple Laravel CRUD with Resources Controllers?

Now, the View app/views/csworks/create.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Cswork App</title>

<link rel=”stylesheet” href=”//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css”>

</head>

<body>

<div class=”container”>

<nav class=”navbar navbar-inverse”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”{{ URL::to(‘csworks’) }}”>cswork Alert</a>

</div>

<ul class=”nav navbar-nav”>

<li><a href=”{{ URL::to(‘csworks’) }}”>View All csworks</a></li>

<li><a href=”{{ URL::to(‘csworks/create’) }}”>Create a cswork</a>

</ul>

</nav>

<h1>Create a cswork</h1>

<!– if there are creation errors, they will show here –>

{{ HTML::ul($errors->all()) }}

{{ Form::open(array(‘url’ => ‘csworks’)) }}

<div class=”form-group”>

{{ Form::label(‘name’, ‘Name’) }}

{{ Form::text(‘name’, Input::old(‘name’), array(‘class’ => ‘form-control’)) }}

</div>

<div class=”form-group”>

{{ Form::label(’email’, ‘Email’) }}

{{ Form::email(’email’, Input::old(’email’), array(‘class’ => ‘form-control’)) }}

</div>

<div class=”form-group”>

{{ Form::label(‘cswork_level’, ‘cswork Level’) }}

{{ Form::select(‘cswork_level’, array(‘0’ => ‘Select a Level’, ‘1’ => ‘Sees Sunlight’, ‘2’ => ‘Foosball Fanatic’, ‘3’ => ‘Basement Dweller’), Input::old(‘cswork_level’), array(‘class’ => ‘form-control’)) }}

</div>

{{ Form::submit(‘Create the cswork!’, array(‘class’ => ‘btn btn-primary’)) }}

{{ Form::close() }}

</div>

</body>

</html>

How to set up a simple Laravel CRUD with Resources Controllers?

To step the form, we will want to validate the inputs and send back error messages if they exist and authenticate against the database, and store the resource if all is good.

Controller Function store()

<?php

/**

* Store a newly created resource in storage.

*

* @return Response

*/

public function store()

{

// validate

// read more on validation at http://laravel.com/docs/validation

$rules = array(

‘name’ => ‘required’,

’email’ => ‘required|email’,

‘cswork_level’ => ‘required|numeric’

);

$validator = Validator::make(Input::all(), $rules);

// process the login

if ($validator->fails()) {

return Redirect::to(‘csworks/create’)

->withErrors($validator)

->withInput(Input::except(‘password’));

} else {

// store

$cswork = new cswork;

$cswork->name = Input::get(‘name’);

$cswork->email = Input::get(’email’);

$cswork->cswork_level = Input::get(‘cswork_level’);

$cswork->save();

// redirect

Session::flash(‘message’, ‘Successfully created cswork!’);

return Redirect::to(‘csworks’);

}

}

Here now you should be able to create a cswork and have them show up on the main landing page!

And navigate to example.com/csworks and there they are.

All that’s left is showing a single csworkupdating, and deleting.

Controller Function show()

<?php

/**

* Display the specified resource.

*

* @param int $id

* @return Response

*/

public function show($id)

{

// get the cswork

$cswork = cswork::find($id);

// show the view and pass the cswork to it

return View::make(‘csworks.show’)

->with(‘cswork’, $cswork);

}

The View app/views/csworks/show.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Cswork App</title>

<link rel=”stylesheet” href=”//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css”>

</head>

<body>

<div class=”container”>

<nav class=”navbar navbar-inverse”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”{{ URL::to(‘csworks’) }}”>cswork Alert</a>

</div>

<ul class=”nav navbar-nav”>

<li><a href=”{{ URL::to(‘csworks’) }}”>View All csworks</a></li>

<li><a href=”{{ URL::to(‘csworks/create’) }}”>Create a cswork</a></li>

</ul>

</nav>

<h1>Showing {{ $cswork->name }}</h1>

<div class=”jumbotron text-center”>

<h2>{{ $cswork->name }}</h2>

<p>

<strong>Email:</strong> {{ $cswork->email }}<br>

<strong>Level:</strong> {{ $cswork->cswork_level }}

</p>

</div>

</div>

</body>

</html>

How to set up a simple Laravel CRUD with Resources Controllers?

Editing a Resource edit()

We, just makes it easier to populate our edit form and you can imagine that when these forms start getting rather bigger this will make life easier.

Controller Function edit()

<?php

/**

* Show the form for editing the specified resource.

*

* @param int $id

* @return Response

*/

public function edit($id)

{

// get the cswork

$cswork = cswork::find($id);

// show the edit form and pass the cswork

return View::make(‘csworks.edit’)

->with(‘cswork’, $cswork);

}

How to set up a simple Laravel CRUD with Resources Controllers?

The View app/views/csworks/edit.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Cswork App</title>

<link rel=”stylesheet” href=”//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css”>

</head>

<body>

<div class=”container”>

<nav class=”navbar navbar-inverse”>

<div class=”navbar-header”>

<a class=”navbar-brand” href=”{{ URL::to(‘csworks’) }}”>cswork Alert</a>

</div>

<ul class=”nav navbar-nav”>

<li><a href=”{{ URL::to(‘csworks’) }}”>View All csworks</a></li>

<li><a href=”{{ URL::to(‘csworks/create’) }}”>Create a cswork</a></lI>

</ul>

</nav>

<h1>Edit {{ $cswork->name }}</h1>

<!– if there are creation errors, they will show here –>

{{ HTML::ul($errors->all()) }}

{{ Form::model($cswork, array(‘route’ => array(‘csworks.update’, $cswork->id), ‘method’ => ‘PUT’)) }}

<div class=”form-group”>

{{ Form::label(‘name’, ‘Name’) }}

{{ Form::text(‘name’, null, array(‘class’ => ‘form-control’)) }}

</div>

<div class=”form-group”>

{{ Form::label(’email’, ‘Email’) }}

{{ Form::email(’email’, null, array(‘class’ => ‘form-control’)) }}

</div>

<div class=”form-group”>

{{ Form::label(‘cswork_level’, ‘cswork Level’) }}

{{ Form::select(‘cswork_level’, array(‘0’ => ‘Select a Level’, ‘1’ => ‘Sees Sunlight’, ‘2’ => ‘Foosball Fanatic’, ‘3’ => ‘Basement Dweller’), null, array(‘class’ => ‘form-control’)) }}

</div>

{{ Form::submit(‘Edit cswork!’, array(‘class’ => ‘btn btn-primary’)) }}

{{ Form::close() }}

</div>

</body>

</html>

Updating a Resource update()

Now, this controller method will process the edit form. It is very easy to store(). And we will validateupdate, and redirect.

Controller Function update()

<?php

/**

* Update the specified resource in storage.

*

* @param int $id

* @return Response

*/

public function update($id)

{

// validate

// read more on validation at http://laravel.com/docs/validation

$rules = array(

‘name’ => ‘required’,

’email’ => ‘required|email’,

‘cswork_level’ => ‘required|numeric’

);

$validator = Validator::make(Input::all(), $rules);

// process the login

if ($validator->fails()) {

return Redirect::to(‘csworks/’ . $id . ‘/edit’)

->withErrors($validator)

->withInput(Input::except(‘password’));

} else {

// store

$cswork = cswork::find($id);

$cswork->name = Input::get(‘name’);

$cswork->email = Input::get(’email’);

$cswork->cswork_level = Input::get(‘cswork_level’);

$cswork->save();

// redirect

Session::flash(‘message’, ‘Successfully updated cswork!’);

return Redirect::to(‘csworks’);

}

}

Deleting a Resource destroy()

In this workflow, you can see a delete button, and click it to delete.

Since we never created a delete button in our app/views/csworks/index.blade.php,

Now, we will create that and we will also add a notification section to show a success message.

The View app/views/csworks/index.blade.php

@foreach($csworks as $key => $value)

<tr>

<td>{{ $value->id }}</td>

<td>{{ $value->name }}</td>

<td>{{ $value->email }}</td>

<td>{{ $value->cswork_level }}</td>

<!– we will also add show, edit, and delete buttons –>

<td>

<!– delete the cswork (uses the destroy method DESTROY /csworks/{id} –>

<!– we will add this later since its a little more complicated than the other two buttons –>

{{ Form::open(array(‘url’ => ‘csworks/’ . $value->id, ‘class’ => ‘pull-right’)) }}

{{ Form::hidden(‘_method’, ‘DELETE’) }}

{{ Form::submit(‘Delete this cswork’, array(‘class’ => ‘btn btn-warning’)) }}

{{ Form::close() }}

<!– show the cswork (uses the show method found at GET /csworks/{id} –>

<a class=”btn btn-small btn-success” href=”{{ URL::to(‘csworks/’ . $value->id) }}”>Show this cswork</a>

<!– edit this cswork (uses the edit method found at GET /csworks/{id}/edit –>

<a class=”btn btn-small btn-info” href=”{{ URL::to(‘csworks/’ . $value->id . ‘/edit’) }}”>Edit this cswork</a>

</td>

</tr>

@endforeach

Now if we click that form submit button, Laravel will use the csworks.destroy route and we can process that in our controller.

Controller Function destroy()

<?php

/**

* Remove the specified resource from storage.

*

* @param int $id

* @return Response

*/

public function destroy($id)

{

// delete

$cswork = cswork::find($id);

$cswork->delete();

// redirect

Session::flash(‘message’, ‘Successfully deleted the cswork!’);

return Redirect::to(‘csworks’);

}

Conclusion

So, we get to know enough so that we can understand and how to resource controllers can be used in all. And just create the single line in the routes file, create the controller, and you have the foundation for doing CRUD.

If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.