CRUD

CRUD

CRUD stand for Create, Read, Update, Delete. This contains the whole roundtrip for a resource. A resource involves (in example of Jobs): show all jobs, show a single job, create a job, store a job (save the newly created job in the database), edit a job, update a job and delete a job.
Here’s how that could look like in your files:

So inside the resources in the view folder you create a new directory for your resource. In this case its jobs (Job) and in there goes everything that involves interacting with said jobs (that need a visual of course). Here’s a list of what the different files contain / do:

  • index.blade.php -> shows all the jobs
  • show.blade.php -> shows a single job
  • create.blade.php -> shows the “Create Job” visual (create & store a job)
  • edit.blade.php -> shows the “Edit Job” visual (edit, update & delete a job)

Here’s another explanation (but only PHP specific nothing with Laravel): Routes & Request Methods

Adjusting the Routes file:

Now when you add new views you of course also need new routes so you can access them. Here’s how you do that:

PHP
// index
Route::get('/jobs', function (){
    $jobs = Job::with('employer')->latest()->paginate(3);

    return view('jobs.index', [
        'jobs' => $jobs
    ]);
});

// create
Route::get('/jobs/create', function (){
    return view('jobs.create');
});

// show
Route::get('/jobs/{id}', function ($id){
    $job = Job::find($id);

    return view('jobs.show', ['job' => $job]);
});

// store
Route::post('/jobs', function () {
    request()->validate([
        'title' => ['required', 'min:3'],
        'salary' => ['required']
    ]);
    Job::create([
        'title' => request('title'),
        'salary' => request('salary'),
        'employer_id' => 1
    ]);

    return redirect('/jobs');
});

// edit
Route::get('/jobs/{id}/edit', function ($id){
    $job = Job::find($id);

    return view('jobs.edit', ['job' => $job]);
});

// update
Route::patch('/jobs/{id}', function ($id){
    request()->validate([
        'title' => ['required', 'min:3'],
        'salary' => ['required']
    ]);
    // authorize (on hold)

    $job = Job::findOrFail($id);

    $job->update([
        'title' => request('title'),
        'salary' => request('salary')
    ]);

    return redirect('/jobs/' . $job->id);
});

// destroy
Route::delete('/jobs/{id}', function ($id){
    // authorize (on hold)

    Job::findOrFail($id)->delete();

    return redirect('/jobs');
});

So as shown above you will need a route for each part of “CRUD”: index (show all jobs), create (create a job), show (show a single job), store (add job to database), edit (edit a job), update (update a job) and destroy (delete a job).

Tags: