Laravel 5.7 CRUD example from scratch

2925
Laravel 5.7 CRUD example from scratch

The Laravel 5.7 was just released and is currently under a hot topic. There are many new features in this latest versions. All the new features and upgrades are discussed in detail in this article. In this article, we are going to implement CRUD example from scratch in Laravel 5.7. If you want to read about

There are certain requirements for installing laravel 5.7. Please take a look at the official documentation.

Create Project

To get started, I have started a fresh laravel project. We can install through composer running the following command:

composer create-project laravel/laravel blog --prefer-dist

Database Setup

Now, we need to setup our database. Create a new database and fill required credentials in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=blog
DB_USERNAME=root
DB_PASSWORD=secret

Create Model and Migration

After database setup, we need to create migration file. To create a migration, run the following command:

php artisan make:model Article -m

This command creates Article model and migration file. We need to add some columns to store our record. So, after some changes our migration file looks like below:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('auther_id');
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

We need to run the migration after these changes.

php artisan migrate

Model

Our table is ready. Now, we need to change our model. After some change, our final model looks like below:


Seeding Database

Let's seed our database. We will use tinker to seed our database. If you want to learn more about tinker, you can read this article How to use Tinker in Laravel Application. First, we create our factory like below:

// database/factories/ArticleFactory.php

define(App\Article::class, function (Faker\Generator $faker) {
    return [
        'author_id' => '1',
        'title' => $faker->sentence,
        'body' => $faker->text,
    ];
});
 

After this setup, we run our command in tinker shell:

factory(App\Article::class, 20)->create();
 

Route

To handle our http request, we need to create our routes. We will use route resources.

Route::resource('articles','ArticleController');

Create Controller

To handle our logics, we will create a new controller through artisan command.

php artisan make:controller ArticleController

We will write some methods to handle our logic and views. Thus, our final controller looks like below:


 $articles]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('articles.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate input fields
        request()->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

        //save data into database
        Article::create($request->all());

        //redirect to article index page
        return redirect()->route('articles.index')
                        ->with('success','Article add successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $article = Article::find($id);

        return view('articles.show', ['article' => $article]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $article = Article::find($id);

        return view('articles.edit', ['article' => $article]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //validate input fields
        request()->validate([
            'title' => 'required',
            'body' => 'required',
        ]);

        //save data into database
        Article::create($request->all());

        //redirect to article index page
        return redirect()->route('articles.index')
                        ->with('success','Article updated successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Article::destroy($id);

        return redirect()->route('articles.index')
                        ->with('success','Article deleted successfully');
    }
}

Create Views

We will create 4 blade files for displaying our all records, showing single record, editing our record and and creating the record.

Index Blade File

This blade file is used to display all our records.



    
        
        
        

        Laravel Blog

        
        
        

    
    
        
        

@if (Session::get('success'))

{{ Session::get('success') }}

@endif
@if(count($articles) == 0) @else @foreach($articles as $key => $article) @endforeach @endif
# Title Content Action
No records found!
{{ (($articles->currentPage() - 1 ) * $articles->perPage() ) + $loop->iteration }} {{ $article->title }} {{ $article->body }} View
Edit
{{ csrf_field() }} {{ method_field('DELETE') }}
{!! $articles->links() !!}

Create Blade File

This blade file is used to display form to create new article.



    
        
        
        

        Laravel Blog

        
        
        

    
    
        
        

Create new article!


@if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif
{{ csrf_field() }}
Cancel

Show Blade File

This blade is used to display a single article.



    
        
        
        

        Laravel Blog

        
        
        

    
    
        
        

Show article

Title: {{ $article->title }}
Body: {{ $article->body }}

Edit Blade File

This blade file is used to edit the article.



    
        
        
        

        Laravel Blog

        
        
        

    
    
        
        

@if ($errors->any())
    @foreach ($errors->all() as $error)
  • {{ $error }}
  • @endforeach
@endif
{{ csrf_field() }}
Cancel

Delete Record

To delete our record, we already added our edit function our index blade file.

{{ csrf_field() }} {{ method_field('DELETE') }}

This is all about coding. Now, let’s test our application. To run the server, simply run the below command:

php artisan serve

After that, we can navigate to our index page http://127.0.0.1:8000/articles Then, we can see the articles list. Similarly, you can test going to different routes.

  • http://127.0.0.1:8000/articles
  • http://127.0.0.1:8000/articles/create
  • http://127.0.0.1:8000/articles/1/edit

Thank you for reading this article. If you find any issue or want to give feedback, please leave a comment below.

LEAVE A REPLY

Please enter your comment!
Please enter your name here