Laravel 4 Mass Assignment Update Google

If you would like to know more about Laravel, watch our Laravel live lesson with Isaac Castillo, teacher of our recent Laravel course.

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.

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 , let’s return a view like this:

And now, in our views directory, let’s create , and enter some starter content:

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:

Now, inside our file, let’s add the service provider to the list:

Let’s add the aliases:

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

Check out this screenshot of our view so far.

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 , 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 method should now look like this:

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

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 method to create a new row in our table. Let’s do that by adding the following to our method. We’ll also redirect back to where we came from:

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 . 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 model will look like:

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:

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 method:

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:

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

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 method to create a new flash message:

Now, we can add this to our blade template:

Here’s what we should see.

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 method, we can now output all tasks that we’ve created so far. Add this to the method:

We can access and output the tasks like this:

Here’s a screenshot for the index view.

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 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 file and extend our master layout:

Now, let’s update our method:

If we navigate to a URL with a random wildcard – – 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 which we can catch. If the record is found, we can access it in our view. Here’s the updated method:

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

Navigate to , and you should see the output.

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

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 file, pull in the master layout, and link the corresponding controller method to it. Here’s the method:

And here’s the view to match:

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 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 and views like this:

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:

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 , 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 , we can update the method to this:

Just like before, if an ID isn’t found, we’ll get the . 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 directive. First, let’s create a folder in our views directory called partials. In there, I’ll create a sub-directory called , and then a file called . Let’s copy over our errors snippet into this new file:

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

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

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

Let’s jump into our 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:

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 method, and handle the record deletion there. Here’s our updated show template incorporating the delete form:

Inside our , we can handle the request in the 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:

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:

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!

Continue learning about Laravel with our Laravel live lesson. One teacher, one lesson, followed by your Laravel questions.

I'm a web designer & developer from Trinidad & Tobago, with a degree in Mechanical Engineering. I love the logical side of the web, and I'm an artist/painter at heart. I endorse progressive web techniques, and try to learn something every day. I try to impart my knowledge as much as possible on my personal blog, callmenick.com. I love food, I surf every weekend, and I have an amazing creative partnership with fellow mischief maker Elena. Together, we run SAYSM.

Laravel 5.3 Form Helpers and CRUD Controller Methods

In this tutorial we are going to build forms in Laravel for creating and editing our data. We will also define all the controller methods required for CRUD operations.

Right now we have out form field in a home.blade.php file. We have the Candidate controller and model set up in PHP on the server side, now it is time to render our markup using Blade Templates.

If you want to follow along the source code is available here: https://github.com/connor11528/laravel-5.3-app (Give it 🌟 on the githubs!)
This is the fourth article working on this codebase. We added authentication, made a typeahead Google Maps component and set up a model + controller in the previous articles.

Use Laravel 5.3 Form Helpers

Laravel Collective maintains Forms & HTML helpers that have been removed from the core framework but are widely used. It helps us write less code and build HTML forms. Install the tool with composer:

Next, add your new provider to the array of config/app.php:

Finally, add two class aliases to the array of config/app.php:

Create the View Files

Let’s create generic files for adding, editing and viewing candidates. You can create these files manually or use the command line as listed below.

$ mkdir resources/views/candidates
$ cd resources/views/candidates
$ touch create.blade.php edit.blade.php form.blade.php index.blade.php show.blade.php

Our views folder now looks something like this:

Create the Candidate Controller methods

In the last post we added a candidate using tinker and mocked out our controller methods but did not fill them out. Below is our CandidateController endpoints as mocked out by Resource Controller. Check out the Eloquent docs and this Scotch.io post for more info about CRUD with Resource Controllers.

Overall we only have to write about 15 lines code. This is enough to Create, Update, Show and Edit data and render our html views. Thank you Laravel.

app/Http/Controllers/CandidateController.php

<?phpnamespace App\Http\Controllers;use Request;
use App\Candidate;class CandidateController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$candidates = Candidate::all(); return view('candidates.index', compact('candidates'));
}/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('candidates.create');
}/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = Request::all();
Candidate::create($input); return redirect('candidates');
}/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$candidate = Candidate::findOrFail($id); return view('candidates.show', compact('candidate'));
}/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$candidate = Candidate::findOrFail($id); return view('candidates.edit', compact('candidate'));
}/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$candidate = Candidate::findOrFail($id);
$input = Request::all();
$candidate->update($input); return redirect('candidates');
}/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$candidate = Candidate::findOrFail($id);
$candidate->delete();

return redirect('candidates.index');
}
}

Note that at the top of the file we use Request instead of Illuminate\Http\Request. This is from these posts on StackOverflow. Redirecting to ‘candidates’ automatically renders the index file in the candidates directory.

Protect from Mass Assignment Vulnerabilities on the Model

We have to tell Laravel that it is okay for users to edit the fields in our database. To do this add a protected field to the model.

app/Candidate.php

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Candidate extends Model
{
// protect from mass assignment vulnerabilities
protected $fillable = [ 'name', 'email', 'phone', 'latitude', 'longitude', 'street', 'city', 'state', 'zip'];
}

If you’re interested to learn more check the docs on mass assignment.

Display Candidate data from the database on the webpage

Our views inherit from resources/views/layouts/app.blade.php. All the content will be rendered in the section in that file where the @yield(‘content’) line is.

We want to get the data from the database on to the screen. The candidates index file will show a list of all the candidates and the show file will show the data for a single candidate. These view will be rendered at http://localhost:8000/candidates and http://localhost:8000/candidates/1.

resources/views/candidates/index.blade.php

@extends('layouts.app')@section('content')
<h1>Candidates</h1>
<div>
@forelse($candidates as $candidate)
<h2>
<a href="{{ url('/candidates', $candidate->id) }}">
{{ $candidate->name }}
</a>
</h2>
<a href="{{ route('candidates.edit', $candidate->id) }}">
Edit candidate
</a>
<div class='body'>
<pre>{{ $candidate }}</pre>
</div>

@empty
<p>There are no candidates to display!</p>
@endforelse
</div>
@stop

The @forelse loop is an elegant solution in Blade for handling cases when the array of data is empty. The url and route methods are different ways of generating links. The <pre> tag is for visualizing the javascript object on the page. It is not pretty but it shows the data for us developer types.

candidates/show.blade.php

@extends('layouts.app')@section('content')
<h1>{{ $candidate->name }}</h1><div class='body'>
<pre>{{ $candidate }}</pre>
</div>
@stop

Add Candidates and Reusing Forms

You may have noticed that we created a form.blade.php. This is a view partial that we will call in both the create and edit views.

resources/views/candidates/create.blade.php

@extends('layouts.app')@section('content')<div class='col-md-6 col-md-offset-3'>
<h1>Add New Candidate</h1><hr>

{!! Form::open(['action' => 'CandidateController@store']) !!}
@include('candidates.form', ['submitButtonText' => 'Add Candidate'])
{!! Form::close() !!}
</div>
@stop

resources/views/candidates/edit.blade.php

@extends('layouts.app')@section('content')<div class='col-md-6 col-md-offset-3'>
<h1>Edit Candidate</h1><hr>

{!! Form::model($candidate, ['method' => 'PATCH', 'action' => ['CandidateController@update',$candidate->id]]) !!}
@include('candidates.form', ['submitButtonText' => 'Edit Candidate'])
{!! Form::close() !!}
</div>
@stop

When we click the create button we’ll get a blank form that goes to the create method in the controller. When we go to the edit page the form will be auto populated with the current data of the record we are editing. The $submitButtonText is defined so the button has the appropriate “create” or “edit” terminology. The form itself is defined below.

resources/views/candidates/form.blade.php

<div class='form-group'>
{!! Form::label('name', 'Name:') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('email', 'Email:') !!}
{!! Form::email('email', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('phone', 'Phone:') !!}
{!! Form::text('phone', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('latitude', 'Latitude:') !!}
{!! Form::text('latitude', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('longitude', 'Longitude:') !!}
{!! Form::text('longitude', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('city', 'City:') !!}
{!! Form::text('city', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('state', 'State:') !!}
{!! Form::text('state', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::label('zip', 'Zip:') !!}
{!! Form::text('zip', null, ['class' => 'form-control']) !!}
</div><div class='form-group'>
{!! Form::submit($submitButtonText, ['class' => 'btn btn-lg btn-success form-control']) !!}
</div>

Note here that we are not using our fancy Vue.js typeahead component here. Ideally we will have the <location-input> component handle filling out the latitude, longitude, state, address and zip. That component is defined in resources/assets/js/components/LocationInput.vue.

0 Replies to “Laravel 4 Mass Assignment Update Google”

Lascia un Commento

L'indirizzo email non verrĂ  pubblicato. I campi obbligatori sono contrassegnati *