PHP
Article

CRUD (Create Read Update Delete) in a Laravel App

By Nick Salloum

How to Build a Basic Laravel CRUD App

In the previous part, we’ve bootstrapped our Laravel CRUD application by creating the database, some controllers, basic routes and simple views. In this part, we’ll wrap things up and implement proper CRUD.

Laravel Logo

If you’d like to follow along through this interactive walk through Laravel’s docs, please catch up by reading the first part now.

Creating A Record

Continuing right where we left off, let’s create the page where we’ll actually perform this action. In our TasksController, let’s return a view like this:

public function create()
{
    return view('tasks.create');
}

And now, in our views directory, let’s create tasks/create.blade.php, and enter some starter content:

@extends('layouts.master')

@section('content')

<h1>Add a New Task</h1>
<p class="lead">Add to your task list below.</p>
<hr>

@stop

At this point, we could manually create a form, but Laravel offers a package to lighten this load for us – Illuminate/Html. Let’s pull that in quickly by running the following command:

composer require illuminate/html

Now, inside our config/app.php file, let’s add the service provider to the list:

'Illuminate\Html\HtmlServiceProvider',

Let’s add the aliases:

'Form'      => 'Illuminate\Html\FormFacade',
'Html'      => 'Illuminate\Html\HtmlFacade',

We can now easily create a form in our create.blade.php file. Let’s go ahead and do that using the form facade and blade syntax:

{!! Form::open([
    'route' => 'tasks.store'
]) !!}

<div class="form-group">
    {!! Form::label('title', 'Title:', ['class' => 'control-label']) !!}
    {!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
    {!! Form::label('description', 'Description:', ['class' => 'control-label']) !!}
    {!! Form::textarea('description', null, ['class' => 'form-control']) !!}
</div>

{!! Form::submit('Create New Task', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

Check out this screenshot of our create view so far.

Create view default

One important thing to note here is that I’ve specified the route on which we will POST to, according to our resourceful routes list. We’ll use the store method to process the data, so let’s head back to our TasksController, and start processing that data.

Let’s turn our heads to requests in Laravel.

The Request facade will grant you access to the current request that is bound in the container.

We can obtain our request instance in two ways, according to the documentation. Let’s stick with the dependency injection method. Our store method should now look like this:

public function store(Request $request)
{
    //
}

Now, we can dump out the information to see what gets posted. We’ll use the helper function, dd(), which is included by default in Laravel. It combines Symphony’s VarDupmer component, and the PHP die function. Add the following to the store method:

dd($request->all());

Now submit the empty form, and you’ll see the data. Go back and fill in some dummy data in the form, and you’ll see the request updated. If we’re not interested in any validation, then saving the new task to the database is easy. In the docs for Eloquent, we’ll notice that we can call the create method to create a new row in our table. Let’s do that by adding the following to our store method. We’ll also redirect back to where we came from:

public function store(Request $request)
{
    $input = $request->all();

    Task::create($input);

    return redirect()->back();
}

We’re ready to create a new task now. Let’s go ahead and enter some dummy data and submit it. Uh oh… there’s a MassAssignmentException. Laravel by default prevents mass assignment, which is a good thing. This just means that we have to declare which fields are mass-assignable. I suggest you read up on this, but here’s what our updated Task model will look like:

class Task extends Model {

    /**
     * Fillable fields
     * 
     * @var array
     */
    protected $fillable = [
        'title',
        'description'
    ];

}

Now, let’s try to add our task again. If we were successful, we should be redirected back to where we came from, i.e. the “create task” page. There’s no indication right now as to whether the task was successfully added, but let’s check the database through the command line:

sqlite3 storage/database.sqlite
select * from tasks;

We should see the table returned with our new entry. Sweet! What about success messages and validation? Let’s first validate our input, to make sure all fields are required. Laravel ships with a really easy-to-use Validator class, and a quick read should have us going in no time. We’re validating in our controller, so let’s look at that section. Let’s validate our input by adding this to the beginning of the store method:

$this->validate($request, [
    'title' => 'required',
    'description' => 'required'
]);

Notice now that if we leave out any of our input, the rest of our method doesn’t execute, and we remain on the page with whatever input has already been entered. Laravel will automatically throw an error, which we can access in our blade template. Let’s insert the following snippet above our form:

@if($errors->any())
    <div class="alert alert-danger">
        @foreach($errors->all() as $error)
            <p>{{ $error }}</p>
        @endforeach
    </div>
@endif

Now, we’ll see the errors neatly written out for us.

Create task errors

What about a success message? Well, if our validator passes, the rest of our code will execute, and we can redirect back with a Session flash message. Update the store method to create a new flash message:

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required',
        'description' => 'required'
    ]);

    $input = $request->all();

    Task::create($input);

    Session::flash('flash_message', 'Task successfully added!');

    return redirect()->back();
}

Now, we can add this to our blade template:

@if(Session::has('flash_message'))
    <div class="alert alert-success">
        {{ Session::get('flash_message') }}
    </div>
@endif

Here’s what we should see.

Create success message

We’re now validating and adding tasks, as well as passing data back to the view for output. Excellent. We still need a way to actually see our records.

Reading Records

Back in our index method, we can now output all tasks that we’ve created so far. Add this to the index method:

public function index()
{
    $tasks = Task::all();

    return view('tasks.index')->withTasks($tasks);
}

We can access and output the tasks like this:

@foreach($tasks as $task)
    <h3>{{ $task->title }}</h3>
    <p>{{ $task->description}}</p>
    <p>
        <a href="{{ route('tasks.show', $task->id) }}" class="btn btn-info">View Task</a>
        <a href="{{ route('tasks.edit', $task->id) }}" class="btn btn-primary">Edit Task</a>
    </p>
    <hr>
@endforeach

Here’s a screenshot for the index view.

Task listing

Let us now figure out how we’re going to display a single record. In this current app, it’s probably not necessary because we’re already outputting all the information, but we’ll do it anyway. If we look at our routes list, it’s apparent that the tasks.show route is the way to go. It accepts a wildcard in the URL, and for our app, we’ll use the ID of the task. As before, we’ll create a show.blade.php file and extend our master layout:

@extends('layouts.master')

@section('content')

<h1>{{ $task->title }}</h1>
<p class="lead">{{ $task->description }}</p>
<hr>

<a href="{{ route('tasks.index') }}" class="btn btn-info">Back to all tasks</a>
<a href="{{ route('tasks.edit', $task->id) }}" class="btn btn-primary">Edit Task</a>

<div class="pull-right">
    <a href="#" class="btn btn-danger">Delete this task</a>
</div>

@stop

Now, let’s update our show method:

public function show($id)
{
    return view('tasks.show');
}

If we navigate to a URL with a random wildcard – /tasks/320918 – we should see our dummy template. Let’s actually fetch the correct task. Using Eloquent, we can search for a record with the matching ID, and if none are found, we’ll throw a ModelNotFoundException which we can catch. If the record is found, we can access it in our view. Here’s the updated method:

public function show($id)
{
    $task = Task::findOrFail($id);

    return view('tasks.show')->withTask($task);
}

Now in our view, we can output the record properly like this:

<h1>{{ $task->title }}</h1>
<p class="lead">{{ $task->description }}</p>

Navigate to tasks/1, and you should see the output.

Single task view

Back in our index view, we can now output the links to each individual task:

<a href="{{ route('tasks.show', $task->id) }}">view</a>

Notice that we passed in the correct wildcard based on the task ID. You should now be able to click through nicely! Let’s move on to editing.

Updating A Record Using Form-Model Binding

By now, you probably realize how easy it is to get a new view ready for our RESTful app. It’s no different this time, so we’ll create the edit.blade.php file, pull in the master layout, and link the corresponding controller method to it. Here’s the edit method:

public function edit($id)
{
    return view('tasks.edit');
}

And here’s the view to match:

@extends('layouts.master')

@section('content')

<h1>Edit Task - Task Name </h1>
<p class="lead">Edit this task below. <a href="{{ route('tasks.index') }}">Go back to all tasks.</a></p>
<hr>

@stop

If you look at the routes list, you’ll notice that the edit route also accepts a wildcard. We’ll be consistent and use the ID. Navigating to /tasks/gibberish/edit will display the dummy page, but let’s pull in the proper content. First of all, we can update all our “edit” links on the index and show views like this:

<a href="{{ route('tasks.edit', $task->id) }}">edit</a>

Notice again how we’re calling the correct route and passing in the corresponding wildcard. In our edit template, we’re going to want a similar form to the one we used to create a task, but it would be pretty useful if the form was already populated with the existing fields. Thanks to Laravel’s form-model binding, this is a piece of cake. We’ll copy over the create form, although a better practice would be to extract this to a partial of some sort. In any case, we’ll copy it over, and bind our model to it:

{!! Form::model($task, [
    'method' => 'PATCH',
    'route' => ['tasks.update', $task->id]
]) !!}

<div class="form-group">
    {!! Form::label('title', 'Title:', ['class' => 'control-label']) !!}
    {!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
    {!! Form::label('description', 'Description:', ['class' => 'control-label']) !!}
    {!! Form::textarea('description', null, ['class' => 'form-control']) !!}
</div>

{!! Form::submit('Update Task', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

Notice how we’re using a PATCH request in the form to stay in line with our RESTful resource. Notice also how we are calling on the variable $task, binding it to the model, and referencing the ID which will be used to look up the table. This means that we have to pass in the correct task. In the TasksController, we can update the edit method to this:

public function edit($id)
{
    $task = Task::findOrFail($id);

    return view('tasks.edit')->withTask($task);
}

Just like before, if an ID isn’t found, we’ll get the ModelNotFoundException. We can, at this point, copy over our errors snippet again, but this isn’t very DRY at all. Don’t worry, we can fix that easily by leveraging partials. Blade allows us to reference any file by using the @include() directive. First, let’s create a folder in our views directory called partials. In there, I’ll create a sub-directory called alerts, and then a file called errors.blade.php. Let’s copy over our errors snippet into this new file:

@if($errors->any())
    <div class="alert alert-danger">
        @foreach($errors->all() as $error)
            <p>{{ $error }}</p>
        @endforeach
    </div>
@endif

Now, we can reference it in any of our files like this:

@include('partials.alerts.errors')

We can now replace the original snippet in our create.blade.php template with this partial reference, and reference it in our edit template as well. The whole edit view should look like this now:

@extends('layouts.master')

@section('content')

<h1>Editing "{{ $task->title }}"</h1>
<p class="lead">Edit and save this task below, or <a href="{{ route('tasks.index') }}">go back to all tasks.</a></p>
<hr>

@include('partials.alerts.errors')

@if(Session::has('flash_message'))
    <div class="alert alert-success">
        {{ Session::get('flash_message') }}
    </div>
@endif

{!! Form::model($task, [
    'method' => 'PATCH',
    'route' => ['tasks.update', $task->id]
]) !!}

<div class="form-group">
    {!! Form::label('title', 'Title:', ['class' => 'control-label']) !!}
    {!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
    {!! Form::label('description', 'Description:', ['class' => 'control-label']) !!}
    {!! Form::textarea('description', null, ['class' => 'form-control']) !!}
</div>

{!! Form::submit('Update Task', ['class' => 'btn btn-primary']) !!}

{!! Form::close() !!}

@stop

Here’s a screenshot of the view when we’re editing a task.

Editing a task

Let’s jump into our update method now, which will receive the data from the form submission, and try to update our record. Like before, we’ll validate our input, and log the errors in our view if any exist. If validation passes, we’ll grab the input, update the task, save it, and redirect back with a success message. Here’s what the method looks like:

public function update($id, Request $request)
{
    $task = Task::findOrFail($id);

    $this->validate($request, [
        'title' => 'required',
        'description' => 'required'
    ]);

    $input = $request->all();

    $task->fill($input)->save();

    Session::flash('flash_message', 'Task successfully added!');

    return redirect()->back();
}

Try it out and see for yourself, it works! You can now create, read, and update records, but let’s cross the final hurdle.

Deleting A Record

Deleting a record RESTfully actually requires a DELETE request. You can get around this outside the controller with JavaScript, but that’s a bit beyond the scope of this article. If we view a single task, you’ll notice that I left a placeholder button there to delete it. We actually need to change this into a form that sends a DELETE request to the destroy method, and handle the record deletion there. Here’s our updated show template incorporating the delete form:

@extends('layouts.master')

@section('content')

<h1>{{ $task->title }}</h1>
<p class="lead">{{ $task->description }}</p>
<hr>

<div class="row">
    <div class="col-md-6">
        <a href="{{ route('tasks.index') }}" class="btn btn-info">Back to all tasks</a>
        <a href="{{ route('tasks.edit', $task->id) }}" class="btn btn-primary">Edit Task</a>
    </div>
    <div class="col-md-6 text-right">
        {!! Form::open([
            'method' => 'DELETE',
            'route' => ['tasks.destroy', $task->id]
        ]) !!}
            {!! Form::submit('Delete this task?', ['class' => 'btn btn-danger']) !!}
        {!! Form::close() !!}
    </div>
</div>

@stop

Inside our TaskController, we can handle the request in the destroy method, rounding off our RESTful controller. Once again, Eloquent makes this a breeze. We’ll fetch the associated record in the table, delete it, and redirect back to the task list:

public function destroy($id)
{
    $task = Task::findOrFail($id);

    $task->delete();

    Session::flash('flash_message', 'Task successfully deleted!');

    return redirect()->route('tasks.index');
}

At this point, let’s refactor our flash message into the master layout file so that it shows up on every template whenever a flash message is posted. We can remove it from the create and edit templates, and keep it only in the master layout like this:

<main>
    <div class="container">
        @if(Session::has('flash_message'))
            <div class="alert alert-success">
                {{ Session::get('flash_message') }}
            </div>
        @endif
        
        @yield('content')
    </div>
</main>

Now, navigate to a task, and delete it. You’ll be redirected back to the task list with a flash message informing you that the task has successfully been deleted. Of course, your task list will be updated to match.

Wrapping Up

We’ve tapped into a lot of core concepts in this tutorial, and touched on a lot of neat Laravel functionality. By building up this CRUD application from scratch, we’ve gotten our taste buds wet with the Laravel workflow.

You should have a solid base and understanding to go on and build something yourself. I highly recommend checking out the various parts of the documentation to see what’s available, and just experimenting around as well. Use this as a building block, and get out there and show off your artisanal spirit. Feedback? Comments? Leave them below!

  • Mouhsine bakhich

    good article ,i think it would be better to put the form inputs in a partial and reuse them instead of duplicating them ,laravel automatically passes data to partials so when we use Form::model() ,form populating will till work.

    • http://callmenick.com Nick Salloum

      That’s a good idea actually, and in a production grade app, that would totally be useful.

  • Tony Marston

    I simply cannot believe how complicated this is and how much code you have to write in order to generate such simple CRUD forms. I don’t develop B2C websites, only B2B enterprise applications, so I have developed a mechanism for generating forms which is far, far quicker and which does not involve writing a single line of code. This mechanism has the following steps
    (1) Create database schema.
    (2) Import database schema into my Data Dictionary.
    (3) Export each table to produce a class file and a structure file.
    (4) Generate a task (which may be a family of tasks) by selecting a database table and one of my Transaction Patterns.
    Steps 2-4 can be done using online forms which have been built into my framework within 5 minutes without having to write a single line of code. The basic forms family is comprised of a LIST1 form which is available on a menu button, and an ADD1, ENQUIRE1, UPDATE1, DELETE1 and SEARCH1 form which are available as navigation buttons within the LIST1 form. These six forms are the simplest patterns available, but my catalogue of 40+ patterns contains variations for different sets of circumstances.
    Changing the database is just as simple – repeat steps 2 and 3 and the structure file will be regenerated without overwriting the class file.
    Why do you have to make such a simple procedure so complicated?

    • Aleksander Koko

      Very interesting. Can you do the same thing on Laravel (as a package using generators) ?

      • Tony Marston

        My technique only works within my own framework as all the components – data dictionary, transaction patterns, etc – do not exist in other frameworks and cannot be ported.

        • CTN

          you should publish your own framework / library

          • Tony Marston

            I did try to publish a link to my framework’s home page, but the moderator removed it.

          • CTN

            is it radicore org ?

          • Tony Marston

            Correct.

    • http://www.skooppa.com s.molinari

      It is because the steps he is describing in the article are only based on CLI helpers from a true PHP framework and not from an application. He is building an application. What you have done is built up a partial administration application on top of your framework. What gives it away?

      “Steps 2-4 can be done using online forms which have been built on top of my framework to help administer it.”

      I’ve corrected the sentence, so it is truer.

      A similar admin application like you’ve built is the Sonata project, built on the Symfony framework.

      https://sonata-project.org/

      And here is a lesser progressed admin application for Laravel4.

      https://github.com/krafthaus/bauhaus

      Their intentions are the same. Make the steps in this article easier, especially for the non-programmer. So, if you want to compare your framework and admin application to anything, you’d need to take Sonata or Bauhaus and compare them.

      Whereas, I already know they won’t be comparable, as they haven’t been around and been worked on for 10 years. Oh, but I’d still take Laravel or Symfony over your framework in a heartbeat, because they don’t have legacy PHP4 code sprinkled all over the place and what I think is a terrible OOP implementation.

      And a website is a website is a website, even if it is for an enterprise application.

    • Tom Berthold

      I agree with Tony. Frameworks are supposed to make a programmer’s life easier. I have noticed that too often I’ve spent WAY too much time figuring out how to accomplish something fairly basic within a framework that could rather easily be accomplished in plain old PHP/MySQL. Do people even feel like they need to learn SQL anymore? It seems everyone wants to use ORM nowadays, and it just doesn’t seem especially efficient to me.

      • http://www.skooppa.com s.molinari

        On the aspect of “Frameworks making a programmer’s life easier”, it naturally depends on what the programmer wants to do. Does she want to build a complex application or just get a simple website up and running. Even then, there are simpler micro-frameworks to help do the simple website too.

        But, for sure, frameworks do help ease the amount of work. Whether or not the solutions offered in the framework you intend to use, are the solutions you also actually want takes a bit of learning and digging into the framework. This work is always necessary, before you decide to use a framework and can, in some cases of a simple application, cause more work than just doing the simple app yourself. I like the trend Symfony is taking, going to a much more modular approach. Pretty soon, we’ll be doing a lot more mixing and matching of modules (or the libraries Tony mentioned) to build up our own frameworks (which is happening in a lot of situations now anyway).

        As for ORMs being more than just SQL, I have to ask, do you really know what the purpose of an ORM is? If you did, you wouldn’t have said that, I think. Yes, in some situations, an ORM isn’t as efficient as directly talking to the database through SQL. Its aim is to simplify the connection between objects and database tables. Another way to put it is to overcome the object relational impedance mismatch.

        http://en.wikipedia.org/wiki/Object-relational_impedance_mismatch

        In other words, it supports the simplification of persisting objects in a more OOP-like fashion and makes it easier to get the programming job done, by worrying less about how the persistence should happen.

        And, the efficient querying of a database is always a performance concern, with or without an ORM (assuming this is what you meant with “efficient”). You can bet though, that performance is always a key concern for the ORM developers and that means, if you use one, you have a group of devs and a ton of users already working for you to improve performance. If you did all the querying on your own, you are on your own. You’d be missing out on all that help. It is one of the great advantages to OSS.

      • Lew Payne

        Tom – You are not alone in agreeing with Tony Marston. I see developers creating all sorts of nonsense (including a bunch of reactive stuff) for business cases that simply don’t need it. The (more often than not, young) developers do it because “it’s the kewl framework” or feature to use. What they completely fail to realize is that most commercial business transactions (especially OLTP) seldom need the reactivity.

        I also find it telling that, in benchmarks, quite often a developer will be asking why some bloated OO framework is slower than “raw” (procedural) PHP, and what they can do to speed up their application. The answer, of course, is get rid of your front controller and start using the built-in path features of your webserver to activate the proper script. The next step is to get rid of the ridiculous OO scripts that can otherwise be replaced by 80 lines (or less) of procedural PHP.

        As for the claim of “OO makes code maintainable, expandable, etc” – good luck with that. Standards and good documentation (beyond a heredoc) are part of what make code maintainable. That, along with a paragraph describing the function (goal) of the code module, is what brings sanity to code. OO certainly has not met it’s promises of “easier to maintain” or “less things break.”

    • Jason Judge

      This example is fairly verbose, and shows just one way in which you can interact in a CRUD way with Laravel. It helps in understanding how the framework works. From there you can approach application design with a deeper understanding of Laravel, and find better and more efficient ways of doing this.

      One thing Laravel does not do, is hold your hand to lead you in implementing in one specific way. It gives you the tools, and gives you some hints on how you could approach a problem, but after that you are left to learn ways of using the framework yourself, or learn from others. Whether you like that approach or not, that is just how Laravel is.

      This tutorial does a great job of showing just one way, and taking care to understand what is happening at each stage helps to understand Laravel better as a whole.

  • Matt B

    Love it! Another good tutorial. I especially like the addition of the session flash message – although I did have an issue with this.
    After completing the “Session” code changes in create.blade.php and TaskController, I was receiving the message “Class ‘AppHttpControllersSession’ not found” after trying to create a new task (which validated correctly). After some searching, adding “use Session;” to the top of the TaskController file worked for me.

    It would be great if you added notes on the ability to enable a minimum number of characters on the title form (for example minimum 3 characters required).

    I’m just trying to teach myself Laravel and this tut helps. I have a question – what exactly do the following do?
    – ServiceProvider
    – FormFacade
    – HtmlFacade

    Eventually (after becoming proficient), I will try to create my own app that I have an idea for. I note that Laravel has recently updated from 4 to 5 – and a lot of the technique and folder structure has changed. I’m finding it hard to find a good articles for L5 (although laracasts helped). Part of my app would be reliant upon stripe integration (I realise I can use “Cashier” but not completely sure how to configure it), and also a membership system whereby particular users are managers; that in turn add users. Other managers cannot see other managers/companies etc. I’m finding it really hard to find some sort of membership system – can you advise? Even better create a tutorial?!!

    Once again, nice tut and keep up the good work.

  • webmachine

    I hope I can ask questions here. I got as far as creating the store method and got this error ”

    FatalErrorException in TasksController.php line 40:
    Class ‘AppHttpControllersTask’ not found” Why is it looking for my Task class in the Controllers folder when it is sitting in the App folder?

    • webmachine

      I asked in the forums and got this answer: http://community.sitepoint.com/t/crud-create-read-update-delete-in-a-laravel-app/191035/3.
      It would have been good to have mentioned this in the article for us who are very new to Laravel. :)

    • http://callmenick.com Nick Salloum

      You have to make sure you make it available. You can do that by writing `use AppTask;` at the top of your file.

      • manjith

        Good and useful tutorial. You used ‘use AppTask;’ for FatalErrorException but i want to know is there another way. if i have 5 model then i have to use ‘use App…’ 5 times. Is there any shorthand declaration? without using ‘use AppTask’. Thanks again for these amazing tutorial.

        • http://www.facebook.com/tahiryasin786 Tahir Yasin

          I believe there is no other way except using ‘use’

      • RoyKusemererwa

        Thanks a bunch for this

  • Sathit Chaiwiwattrakul

    Hi All, I follow step by step and got error in this step.

    // TasksController.php
    public function store(Request $request)
    {
    $input = $request->all();
    Task::create($input);
    return redirect()->back();
    }

    after submit form, I got this error

    FatalErrorException in TasksController.php line 39:
    Class ‘AppHttpControllersTask’ not found

    What wrong with my code?

    • Nadeem

      Add this line in top of your taskController
      use AppTask;

    • Prajwol K.C

      i am also getting the same issue

      • Sathit Chaiwiwattrakul

        add

        use AppTask;

        on top of controller file

        • Dave Jong A Lock

          Hi Nadeem or Sathit,

          I tried this, but it still doesn’t work. I had to change it to:
          $tasks= AppTask::all();

          in all references to the task class. I would like another option.

          I think in the same manner I am having difficulties with the Session class. I cannot refer to it in my controllers, any help would be appreciated.

          thanks,

          Dave

          • Dave Jong A Lock

            All,

            I found my mistake. The line needs to be beneath

            namespace AppHttpControllers;

            otherwise it doesn’t work.

            regards,

            Dave

    • http://callmenick.com Nick Salloum

      @sathitc:disqus and @Nadeem both gave the right answer. Thanks guys.

      • Dave Jong A Lock

        Hi Nick,

        I tried this, but it still doesn’t work. I had to change it to:
        $tasks= AppTask::all();

        in all references to the task class. I would like another option.

        I think in the same manner I am having difficulties with the Session class. I cannot refer to it in my controllers, any help would be appreciated.

        thanks,

        Dave

        • Edgar Martin del Campo Rojas

          just add this in top of your TasksController.php as somebody said before:

          use AppTask;

          use Session;

  • Tony Marston

    > It is because the steps he is describing in the article are only based on CLI helpers from a true PHP framework and not from an application.

    It is clear that you do not understand the difference between a framework and a library. If you have to write your own code to call the framework components, then it is not a framework, it is a library. A “true” framework is in fact a mini-application with which you should be able to both generate and run your application components.

    > He is building an application. What you have done is built up a partial administration application on top of your framework.

    We are both building a set of CRUD screens which in themselves do not form a complete application, just only a small part. There are two major differences:

    1) Nick’s method requires the developer to write an enormous amount of code whereas my method requires none – no PHP code, no HTML code, no SQL code.

    2) Nick’s method is limited to the basic Browse, Create, Read, Update and Delete screens whereas mine also includes a Search screen. Each of these is provided from one of my Transaction Patterns, and apart from these 6 basic patterns I have over 30 more which cater for different scenarios.

    Using my 40+ transaction patterns I have built a large enterprise application which uses over 300 database tables and 2,500 user transactions. I hate to think how long this would have taken using Nick’s method.

    > And a website is a website is a website, even if it is for an enterprise application.

    I disagree. A public-facing website has totally different needs from a business-facing enterprise application as I have described in http://www.tonymarston.net/php-mysql/web-site-vs-web-application.html

    • http://www.skooppa.com s.molinari

      >It is clear that you do not understand the difference between a framework and a library. If you have to write your own code to call the framework components, then it is not a framework, it is a library. A “true” framework is in fact a mini-application with which you should be able to both generate and run your application components.

      That is your definition of a framework and it is absolutely WRONG!

      http://en.wikipedia.org/wiki/Software_framework

      “In computer programming, a software framework is an abstraction in which software providing generic functionality can be selectively changed by additional user-written code, thus providing application-specific software.”

      “changed by additional user-written code”. Sounde like “write your own code to call the framework components” to me.

      http://www.jfwk.com/what_is.html

      “A framework is a set of common and prefabricated software building blocks that programmers can use, extend or customize for specific computing solutions. With frameworks developers do not have to start from scratch each time they write an application. Frameworks are built from collection of objects so both the design and code of the framework may be reused.”

      “programmers can use, extend or customize for specific computing solutions” “both the design and code of the framework may be reused”

      Also sounds like code is needed to call, extend or reuse the framework components.

      Care to change your opinion? You are wrong. Seriously wrong.

      >I disagree. A public-facing website has totally different needs from a business-facing enterprise application

      Needs are one thing. The architecture needed to build either of them is what I am talking about and it is the same. Oh, btw, just about any serious website software/ application has a “back-end” too, which fits all your “back-end needs”.

      • Tony Marston

        > “changed by additional user-written code”. Sounde like “write your own code to call the framework components” to me.

        It depends entirely on how it is implemented. In my own framework my abstract class contains empty methods which are called at certain stages in the processing of a request. All the developer has to do is copy the empty method into his concrete class, fill it with code, and at runtime this “custom” method will override the empty method in the abstract class. Using this technique I have also allowed the option for a custom method to be called either before, after or instead of a standard method. This clearly demonstrates how it is the framework that calls the user-land code and not the other way around.

        > Also sounds like code is needed to call, extend or reuse the framework components.

        Wrong. The framework handles all the standard processing, and it is up to the developer to create “custom” methods to either extend or replace this standard behaviour.

        > The architecture needed to build either of them is what I am talking about and it is the same.

        I disagree. I have been building enterprise applications for over 30 years, and absolutely none of the current batch of front-end frameworks can provide what is needed in a true enterprise application.

        > Oh, btw, just about any serious website software/ application has a “back-end” too, which fits all your “back-end needs”.

        I disagree. A few CRUD screens at the back-end does not constitute an enterprise application. You need to take a look at http://en.wikipedia.org/wiki/Enterprise_software

  • Sathit Chaiwiwattrakul

    How can I handle ModelNotFoundException

    if I open the id which not exists in database, for example
    http://localhost:8000/tasks/25585

    • http://callmenick.com Nick Salloum

      You can do a try catch, and use a helper function to handle errors.

  • kyantkhine

    After i create new task is successful complete but the redirect link is not working, then i click F5 to reload but not working.
    I select the current url in the browser address bar and enter. It is woking.
    How do i solve this issue?

  • http://www.skooppa.com scamo

    Tony, as usual, you twist and bend what I say to fit your own prerogatives and thus, it is impossible to have any kind of decent discussion with you. You not only do this with what I say, but with everything you get recite as a resource. You should really stop looking at things through your very narrow glasses and try to take them off just for a minute and see a much more open and colorful world.

  • http://www.skooppa.com scamo

    My comment was aimed at your last comment. But nevermind. You can certainly continue to live in your own world, and the rest of us will live in the real world.

  • http://www.skooppa.com scamo

    My whole reply is based purely on a core framework and the definition of a framework. Your definition is not the definition of a framework, but rather more towards an application or a RAD framework, which is also partly an application. And as usual, your opinion is solely focused on your own world of what you think a framework should be and how it solves some enterprise problems. That world is why you end up twisting things around.

    Whereas, the truth is, any good PHP framework can also solve those same problems. It might not be as easy as with your framework and it also means more work, as you’ve pointed out, but that more work also means more flexibility for the developer, which a good framework should typically offer.

    I’d also venture to say, using a good modern PHP framework like Symfony, over time, would actually be much more efficient than using your old antiquated framework Tony, simply because they properly follow modern OOP methodologies and are built for unit testing, which yours isn’t. Oh, and of course, there are tons and tons a tons of bundles and libraries, which can be added to Symfony with very little trouble.

    There is no argument you can come up with that can counter that truth and why any serious developer today wouldn’t touch your framework with a 10 foot pole. I am not saying that to hurt you Tony, but rather to get you hopefully wanting to change. And my biggest wish would be, until you do accept that things have changed and you want to change yourself, you leave your comments to yourself, because they help no one and you try to help no one with them. You only try to help yourself and your fight to prove your framework has a right to exist.

    It was absolutely right that the mods here removed the link to your framework. Not because it was a bit of spamming, but because nobody should even come into contact with it. If anything, it is a great example of how NOT to do programming today. Again, I am not trying to attack you Tony, I really am not. I am seriously trying to get you to change your dreaded down in a very deep old hole and hermit-like perspective.

    I bet, if you decided today, you’d throw away all your work, (yes, I understand it is a very, very hard decision) and rebuild a new RAD enterprise application with Symfony, and you’d learn the modern methods of OOP in PHP, including unit testing, that with your experience and background (but changed perspective), you could rewrite the Radicore Framework in about a year to a year and a half and it would be miles better than what you have now. Miles better! I challenge you to do it. I’d really love to see it happen, so you can then be a helpful developer in the community and not an outcast.

    • Tony Marston

      > My whole reply is based purely on a core framework and the definition of a framework. Your definition is not the definition of a framework, but rather more towards an application or a RAD framework, which is also partly an application.

      I disagree completely. The Wikipedia article at http://en.wikipedia.org/wiki/Software_framework clearly says the following:

      Frameworks contain key distinguishing features that separate them from normal libraries:

      1) inversion of control: In a framework, unlike in libraries or normal user applications, the overall program’s flow of control is not dictated by the caller, but by the framework.

      2) default behavior: A framework has a default behavior. This default behavior must be some useful behavior and not a series of no-ops.[citation needed]

      3) extensibility: A framework can be extended by the user usually by selective overriding or specialized by user code to provide specific functionality.

      4) non-modifiable framework code: The framework code, in general, is not supposed to be modified, while accepting user-implemented extensions. In other words, users can extend the framework, but should not modify its code.

      My framework has those features, so it IS a framework and NOT a library. The fact that it is also a mini-application in its own right is not an issue, in fact it is a requirement of a framework in order satisfy point #1 above.
      The fact that you (and others like you) don’t like the way I write code is irrelevant. Just because I don’t follow the same dogmatic rules as you does not mean that my code is automatically crap, it just means that, as a pragmatic programmer, I put results before rules, and I can produce better results by following different, less restrictive rules.
      I still say that a true enterprise application is totally different from a public-facing website, so it has totally different needs, and those needs can best be served by a specialist framework. Although it may be possible to write an enterprise application using a front-end framework such as Laravel, Symfony, Codeigniter, Zend, et al, it will require significantly more effort. What you can do with your framework I can do quicker and cheaper with mine, and that impresses potential customers more than the code having been written “properly” using a “proper” framework.
      The fact that you choose to use this forum to attack both me and the way I write code is totally out of order. Please desist.

      • V Arun Kumar

        I Learned a Lot by reading this thread. i wish to see you both again

    • Tony Marston

      > Whereas, the truth is, any good PHP framework can also solve those same problems.
      I disagree. If you have to write code to access the framework’s components then it is not a framework, it is a library. A true framework generates components with default behaviour, and the only code to have to write is to override or extend that default behaviour. My framework can generate default components without the need to write a single line of code – no PHP, no HTML, no SQL. Can yours?

      • http://www.skooppa.com scamo

        You see, now we’ve come full circle. Reread the definition of what a software framework is. It is a set of modules (which can be libraries), where a “client coder” calls on (with code) to perform tasks to get an application job done. If you look at Laravel or Symfony, they have a good number of components or libraries in them and are built to help a programmer put together an application… faster. That is the definition of a framework. Your definition of a framework is based more on RAD Tony and just because it is based on that definition, doesn’t mean the real definition of a framework is wrong. You say it is, but you are wrong by saying that. Terribly wrong in fact and why I said all the things above. You really need to come out of your misinformed and skewed world and stop wasting people’s time, even if it is to only read your misinformation.

        • Tony Marston

          The Wikipedia definition of a software framework at http://en.wikipedia.org/wiki/Software_framework distinctly says libraries and frameworks are NOT the same thing.:

          “In a framework, unlike in libraries or normal user applications, the overall program’s flow of control is not dictated by the caller, but by the framework”
          This means that the follow of control is handled by the framework, not the user, which means that it is the framework which calls the user’s code, not the other way around. If the flow of control is handled by the user, where the user’s code calls the framework’s components, the “it” is not a framework, it is a library. So how does my definition of a framework differ from the Wikipedia description?

        • Tony Marston

          > Your definition of a framework is based more on RAD .

          I disagree completely. The Wikipedia article at http://en.wikipedia.org/wiki/Software_framework clearly says the following:

          Frameworks contain key distinguishing features that separate them from normal libraries:

          1) inversion of control: In a framework, unlike in libraries or normal user applications, the overall program’s flow of control is not dictated by the caller, but by the framework.

          2) default behavior: A framework has a default behavior. This default behavior must be some useful behavior and not a series of no-ops.

          3) extensibility: A framework can be extended by the user usually by selective overriding or specialized by user code to provide specific functionality.

          4) non-modifiable framework code: The framework code, in general, is not supposed to be modified, while accepting user-implemented extensions. In other words, users can extend the framework, but should not modify its code.

          My framework has all those features, so it IS a framework and NOT a library. The fact that it is also a mini-application in its own right is not an issue, in fact it is a requirement of a framework in order satisfy point #1 above.

          The fact that you (and others like you) don’t like the way I write code is irrelevant. Just because I don’t follow the same dogmatic rules as you does not mean that my code is automatically wrong, it just means that, as a pragmatic programmer, I put results before rules, and I can produce better results by following different, less restrictive rules.

          I still say that a true enterprise application is totally different from a public-facing website, so it has totally different needs, and those needs can best be served by a specialist framework. Although it may be possible to write an enterprise application using a front-end framework such as Laravel, Symfony, Codeigniter, Zend, et al, it will require significantly more effort. What you can do with your framework I can do quicker and cheaper with mine, and that impresses potential customers more than the code having been written “properly” using a “proper” framework.

        • Tony Marston

          > Your definition of a framework is based more on RAD

          I disagree completely. The Wikipedia article at http://en.wikipedia.org/wiki/Software_framework clearly says the following:

          Frameworks contain key distinguishing features that separate them from normal libraries:

          1) inversion of control: In a framework, unlike in libraries or normal user applications, the overall program’s flow of control is not dictated by the caller, but by the framework.

          2) default behavior: A framework has a default behavior. This default behavior must be some useful behavior and not a series of no-ops.

          3) extensibility: A framework can be extended by the user usually by selective overriding or specialized by user code to provide specific functionality.

          4) non-modifiable framework code: The framework code, in general, is not supposed to be modified, while accepting user-implemented extensions. In other words, users can extend the framework, but should not modify its code.

          My framework has all those features, so it IS a framework and NOT a library. The fact that it is also a mini-application in its own right is not an issue, in fact it is a requirement of a framework in order satisfy point #1 above.

          The fact that you (and others like you) don’t like the way I write code is irrelevant. Just because I don’t follow the same dogmatic rules as you does not mean that my code is automatically wrong, it just means that, as a pragmatic programmer, I put results before rules, and I can produce better results by following different, less restrictive rules.

          I still say that a true enterprise application is totally different from a public-facing website, so it has totally different needs, and those needs can best be served by a specialist framework. Although it may be possible to write an enterprise application using a front-end framework such as Laravel, Symfony, Codeigniter, Zend, et al, it will require significantly more effort. What you can do with your framework I can do quicker and cheaper with mine, and that impresses potential customers more than the code having been written “properly” using a “proper” framework.

    • Tony Marston

      My reply to scamo’s post which insulted both me and the quality of my work has been removed by the moderator. If I am prevented from replying to such an insulting post then I demand that the insulting post be removed.

      • http://www.skooppa.com scamo

        Tony, I don’t mean to insult you and I wish you wouldn’t take it that way. My personal wish is for you to change. Or, simply stop arguing about the way coding practices are done now, by always comparing them to your own legacy code and at the same time NOT excepting the fact it is old code with old methodologies. It just isn’t right or fair and you end up possibly misleading people, who are less in the know. You are doing both yourself and the PHP community a disservice. If you want to argue about the status quo, then leave out your framework from the discussion completely and argue on the basis of code snippets or some other resources. Leave your framework out of the picture. If you do that, you’ll probably find your arguments and the reasons for them are weak to nonexistent.

  • markmanley

    Hi – thanks for the tutorial. Complete noob here. So an issue with the form – I recognize that the Illuminate library for form and html are deprecated, so I followed the laravelcollective instructions and quad-checked them, but still getting this message: “Class ‘CollectiveHtmlHtmlServiceProvider’ not found”. gAny ideas where else to look? I updated composer.json in vendor directory, along with the config/app.php, and I ran composer update. Thanks in advance!

  • http://www.skooppa.com scamo

    >My framework has all those features, so it IS a framework and NOT a library.

    Who said your framework is a library? Making a point again, when there never was one.

    >The fact that you (and others like you) don’t like the way I write code is irrelevant.

    It is not that we don’t like the way you write code, it is your code isn’t written to modern standards and best practices. You can argue all you want about those practices being right or wrong, but they are there and are prevalent and when you reference them against your framework, your code is badly legacy and you look foolish and at times arrogantly ignorant. The fact your framework functions is irrelevant from a developer’s standpoint today.

    As for your last paragraph. You are the one saying frameworks like Laravel and Symfony aren’t frameworks, but rather libraries, because client coders have to do more work with them. You are right about the more work, but are wrong about them not being frameworks. They meet all of the 4 points you quoted from Wikipedia.

    • Tony Marston

      > Who said your framework is a library?

      You said “Your definition is not the definition of a framework” which implies that, as my framework has all the characteristics of that incorrect definition, that it is not actually a framework. If it is not a framework then this implies that it must be the alternative, which is a library.

      > It is not that we don’t like the way you write code, it is your code isn’t written to modern standards and best practices.

      It most certainly *IS* written to follow best practices, it’s just that they are not the same practices that you follow. There is no single set of “best practices” which is universally accepted by all programmers just as there is no single religion which is universally accepted as the only “true” religion.

      As for “modern standards” you actually mean “fashionable standards”, but fashions have a habit of appearing and disappearing with regular monotony. I prefer to write “functional” software which has value in the eyes of my customers.

      > The fact your framework functions is irrelevant from a developer’s standpoint today.

      I disagree. I write software to impress the customers who pay my wages, not a bunch of developers who keep arguing over trivialities. My framework allows me to create applications faster and cheaper and with more features than other so-called frameworks, which means that in the eyes of my customers my framework has more value than those others.

      • http://www.skooppa.com scamo

        Whatever Tony. I concede to your ignorance and unwillingness to accept that the way PHP is being coded today is considerably better than what you have built many moons ago.

        • Tony Marston

          I may have designed and built in many moons ago, but I have been actively maintaining and extending it ever since. Just because I choose to write my code in a different from you does not mean that my code is automatically bad. Anyone who believes that their style of writing code is the only acceptable style is being unbelievably juvenile. I write code which is functional, not fashionable. I write code to please my paying customers, not some know-it-all developers.
          This thread is supposed to be about developing CRUD applications with frameworks, so you have no right to use it to attack how I write my code.

          • http://www.skooppa.com scamo

            Like I said, you defy accepting that fact that the way PHP is developed today is actually much better than the way you code, ok, even now. You use monster 9000 line classes. You still have PHP4 constructors. You don’t use namespaces. You don’t use autoloaders. You don’t unit test. (And stop with the “I don’t have the problems those things solve BS.) Those are just a few reasons for any of today’s devs to avoid your framework like the plague. The only reason there is for any “attacking” is your own lack of admittance that your coding methods got stuck in the mid 2000’s and never advanced and your insatiable desire to have to compare your framework to everything done today (like your first comment here) and your attempts to talk down what is being done.

            Answer this one question Tony. If your framework is so good, why aren’t developers jumping all over it like they are with Laravel or Symfony? And don’t come up with, because it is for “Enterprise Apps”. That, as a reason, is a load of bull hockey.

          • Tony Marston

            > Like I said, you defy accepting that fact that the way PHP is developed today is actually much better than the way you code, ok, even now.

            How each individual developer uses the features of a programming language to produce results is irrelevant. There is no such thing as a single “style” (or best practices) which is universally accepted by all developers.

            > You use monster 9000 line classes.

            Incorrect. I have only one class of that size, and it is an abstract class, not a concrete class. It is inherited by every one of my 300+ Model (Business layer) classes, Inheritance is a recognised technique in OOP for sharing code, so all I am doing is sharing 120+ methods and 9,000 lines of code, so what is wrong with that?

            > You still have PHP4 constructors.

            So what? You forget that for many years I had to support both PHP4 and PHP5 sites from a single codebase, and PHP4 constructors have NEVER been deprecated in ANY version of PHP5.

            > You don’t use namespaces.

            So what? I don’t NEED them, so I don’t use them.

            > You don’t use autoloaders.

            So what? I don’t NEED them, so I don’t use them.

            > You don’t unit test.

            TDD is a design tool, and as an experienced designer I don’t need it. Besides, it is far too expensive to retro fit into an existing and very large application.

            > The only reason there is for any “attacking” is your own lack of admittance that your coding methods got stuck in the mid 2000’s and never advanced

            I am a pragmatist, not a dogmatist, so the rules I follow to produce results are less important than the results themselves. I write code to please my paying customers, not some know-it-all developers

            > If your framework is so good, why aren’t developers jumping all over it like they are with Laravel or Symfony?
            Because 99.9% of PHP developers do nothing but develop public-facing websites whereas I develop business-facing enterprise applications which are up to 100 times larger and have totally different needs. I have also noticed that 99.9% of developers cannot think for themselves and follow like sheep. They look at the download counts for different frameworks and say “That one has the most downloads, so it must be the most popular”. Or they are stuck with the framework that their employer has chosen.
            The fact that there aren’t millions of developers using my framework to build enterprise applications doesn’t bother me in the least. It simply means that there is almost no competition for my own enterprise application, a fact that makes my business partner (who helps me to sell it to large corporations all the world) rub his hands with glee as he makes another sale.

          • http://www.skooppa.com scamo

            Well, I am glad your framework gets NO real attention from the PHP community. Have fun Tony, until we meet in some other thread again.

  • http://www.agriya.com/services/yii-development jennifermorrison

    Amazing article! Nice Thought! Keep it up!

  • juantonio v

    hi!! Here I leave the code https://github.com/JuanVqz/crud5, thanks for your time Nick, good tutorial.

  • Stephen Higgins

    Hi,

    I’m not sure if this has already been addressed in the previous comments, but the references to FormFacade and HtmFacade from app.php in the example aren’t compatible with Laravel 5.1.

    They should now be, under ‘providers’:

    IlluminateHtmlHtmlServiceProvider::class,

    Under ‘aliases’:

    ‘Form’ => IlluminateHtmlFormFacade::class,
    ‘Html’ => IlluminateHtmlHtmlFacade::class,

    Thanks.

    Great tutorial.

    • http://www.fititnt.org Emerson Rocha Luiz

      Thanks. This change is really need for Laravel 5.1. Tested here.

  • smallcog

    Hello,
    is there any chance of providing the source files from the tutorial, something that would get the crud app up and running quickly and allow tinkering to begin ?

    Best regards,

    Colm

  • smallcog

    If there’s one thing I love more than great tutorials, its great tutorials that provide all the source code.

    When you’re a beginner, it’s great to have something to reference against, it’s so frustrating to type things in manually, have some “simple” newbie error set you back and then lose all hope.

    Please, please / Colm

  • James Buretta

    Thank you very much for such an amazing tutorial , it really helped me alot to have the light on how to use laravel, may God almighty bless you

  • gatzmar

    Do you have tutorial in login system for admin and user sir?

  • khudadad

    Great tuts
    Thanks

  • Sprime

    Thank you!

  • chollie

    Great tutorial. Thank You.

  • Isran Irawan

    how about route.php setting?

  • http://noelgarcia.me/ Noel Andrés García Carrillo

    Great tutorial! Thanks a lot!!

  • RoyKusemererwa

    Thanks Nick, yo the best, thumbs up for this

  • Zen

    Whoah! I just found an ease with Laravel!

  • Lorddonk

    You are AWESOME! Seriously this is probably the best tutorial there is. I have followed along with other tutorials, videos, and even the docs, and none of them are explained this well and with 100% accuracy.

    I followed similar tutorials and found issues even with copy and pasting their exact code. And none of them actually explained things this well!

    Just wanted to drop you a line and say that I really appreciated this and probably would have frustratingly dropped Laravel if not for finding your tutorial. I hope you will have more tutorial in the future to look for. With this one you covered most of the basics and have set me on my way to being able to make something! Thank you!

  • Senghok Eang

    complete laravel ajax CRUD operation with search, sort and pagination
    https://laracast.blogspot.com/2016/06/laravel-ajax-crud-search-sort-and.html

  • dhaval dobariya

    It’s awesome article best for begineer

  • Ben Wilson

    Great tutorial. Well written and easy to understand.

  • Riyaz Khan

    This artice really change my Laravel life… I would strongly
    recommend to all Laravel beginner. Hats off to you Nick. Actually how
    laravel CRUD and itself larvel how does works, this concept is cleared
    by only you.

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in PHP, once a week, for free.