I am trying to update the record in the database. This is a specific element that is an element of another. Here is my code, it doesnt work :/
web.php :
Route::patch('/projects/{projectID}/{id}', 'ProjectsController#update');
Controller:
public function update($projectId, $id, CreateProjectRequest $request)
{
$page = Page::findOrFail($id);
$page->update([
'name' => $request->name,
]);
return redirect('/projects/' . $projectId);
}
HTML:
{!! Form::model($page, ['method'=>'PATCH', 'action' => ['ProjectsController#update', $project->id, $page->id]]) !!}
{!! Form::text('name',null,['class'=>'blue-inp']) !!}
{!! Form::submit('Save changes',['class'=>'btn btn-save-blue']) !!}
{!! Form::close() !!}
You need to switch the class type-hint CreateProjectRequest for just Request in your controllers update method.
The variables passed from the form input fields can then be accessed like this:
$name = $request->input('name');
More on the topic: https://laravel.com/docs/5.0/requests
You can simplify the controller method, assuming the CreateProjectRequest handled all the necessary validation and it's inputs match the inputs you want to update
Edit: I prefer to validate everything with formrequests with rules and by the time it reaches the controller, it just calls services or does stuff.
As far as naming conventions, you may not need to send the $id in the url parameter and send it within the body, in order to avoid using Request in the formrequest to validate if it exists in the database
public function update($projectId, $id, CreateProjectRequest $request)
{
$data = $request->validated();
Page::findOrFail($id)->update($data);
return redirect('/projects/' . $projectId);
}
Related
I am very new in Laravel. I'm trying to bind a property of the Model to selected values of the select tag. now, the following code can not show the selected tags.
{!! Form::label('tag_list','Tags') !!}
{!! Form::select('tag_list[]',$tags, null,['class'=>'form-control','multiple']) !!}
when I gave
{!! Form::label('tag_list','Tags') !!}
{!! Form::select('tag_list[]',$tags, [1,2,3],['class'=>'form-control','multiple']) !!}
it worked.
in model Article I have
public function getTagListAttribute()
{
return $this->tags->lists('id')->all();
}
this does not help. In some thread I found that for Laravel 5.2 pluck should work instead of list.
so I tried
public function getTagListAttribute()
{
return $this->tags()->pluck("id")->toArray();
}
I am using Laravel 5.2.39. What am I missing?
The third parameter of the select() method should contain the default value(s) of the select. You're passing null so there are no default values which will be selected automatically.So that it gives you error.
You can write your model as
public function getTagListAttribute()
{
return $this->tags->lists('id')->toArray();
}
Using Laravel 5 I m trying to delete a single record within a controller, here is my code:
public function destroy($id)
{
$employee = Employee::find($id);
$employee->delete();
return Redirect::route('noorsi.employee.index');
}
My view page code is:
<td>Delete</td>
My route is:
Route::delete(employee.'/{id}', array('as' => 'noorsi.employee.destroy','uses' => Employeecontroller.'#destroy'));
That did not work.
How do I fix the implementation ?
From the official Laravel 5 documentation:
Delete an existing Model
$user = User::find(1);
$user->delete();
Deleting An Existing Model By Key
User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);
In every cases, the number between brackets represents the object ID, but you may also run a delete query on a set of models:
$affectedRows = User::where('votes', '>', 100)->delete();
http://laravel.com/docs/5.0/eloquent#insert-update-delete
So the Laravel's way of deleting using the destroy function is
<form action="{{ url('employee' , $employee->id ) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Employee</button>
</form>
You can find an example here http://laravel.com/docs/5.1/quickstart-intermediate#adding-the-delete-button
And your route should look something like this
Route::delete('employee/{id}', array('as' => 'employee.destroy','uses' => 'Employeecontroller#destroy'));
It works with eg:Route::resource('employee', 'EmployeeController'); and it should also work with how you set up your destroy route.
Obviously you have a bad routing problem. You're trying to use a 'get' verb to reach a route defined with a 'delete' verb.
If you want to use an anchor to delete a record, you should add this route:
Route::get('/employee/{id}/destroy', ['uses' => 'EmployeeController#destroy']);
or keep using a delete verb, but then you need to use a form (not an anchor) with a parameter called _method and value 'delete' stating that you're using a 'delete' verb.
Route::get('/showcon/{del_id}/delete','MainController#deletemsg');
public function deletemsg($del_id){
$mail=Mail::find($del_id);
$mail->delete($mail->id);
return redirect()->back();
}
del
I am working in a Laravel 5 application. I try to save a comment for a projet and I don't know how to get the $comment->project_id value.
Here is my simplified controller
public function store( CommentsFormRequest $request )
{
$comment = new Note;
$comment->message = Input::get('message');
$comment->project_id = $note->project->id;
$comment->user_id = Auth::id();
$comment->save();
return Redirect::back();
}
and here is my simplified form
{!! Form::open(array('route' => 'notes.store')) !!}
{!! Form::textarea('message', '', array('placeholder'=>'Message')) !!}
{!! Form::submit('Ajouter la note') !!}
{!! Form::close() !!}
When I try to save, I get this error:
Trying to get property of non-object
I guess it's because it tries to get the sollicitation_id of the new object wich is null. How should I get the current project_id value?
Update
Conclusion: I used an hidden field and followed #tommy 's recommendation.
My controller now uses
$note->project_id = $request->input('project_id');
and my hidden field is
{!! Form::hidden('project_id', $project->id ) !!}
Only IF the table primary column name is 'id':
$model->id;
Regardless of primary column name:
$model->getKey();
In the store method, you try to get the property project of the variable $note, which does not exist. You should pass the project ID to the store method by either adding it to the route or adding a hidden field project_id to your form.
Then, your store method should look something like this:
public function store($project_id, CommentsFormRequest $request )
{
$project = Project::find($project_id); // $project_id is transmitted over the URL
$comment = new Note; // I'd alias Note as 'Comment', or rename '$comment' to '$note' because this can be confusing in the future
$comment->project_id = $project->id;
$comment->save();
return Redirect::back();
}
If you want to add a hidden field with the project ID to the form, you can access its value by calling $request->input('project_id');
I feel the above answer is far from perfect as you're not only exposing Unique ID's to users but it's also long winded, and would fail if two users were to load the same page at the same time, instead you should do
public function store(CommentsFormRequest $request )
{
$comment = new Note([
// your fields here
]};
$comment->save();
//$comment now contains a unique ID!
return redirect($comment->id);
}
You can get last id by using insertGetId() Query Builder method
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
for more info check document
I'm new to php platforms and what I'm trying to do is to pass a variable from the controller to view for populating a dropdown list with entries from the database, but whatever i'm trying is not working. I get the following error:
Undefined variable: products_create
I can't understand what I'm doing wrong.
Controller
public function create()
{
$products_create = categories::all(['id', 'category']);
return View::make('products.create', compact('id', 'category'));
}
View
{!! Form::label('category', 'Categorie') !!}
{!! Form::select('category', $products_create) !!}
You pass variables to a view in the form of an associative array:
return View::make('products.create', ['products_create' => $products_create]);
compact is a function that helps you build such an array where all keys are the same as the variable name. However you have to pass the actual variable name to the function:
return View::make('products.create', compact('products_create'));
To pre-populate form field, we can add 'value' to form field in create.blade.php:
{{ Form::text('title', 'Some default title') }}
Is there a way to do that task elsewhere (maybe in model or controller?). I'd like to have code for form fields identical in create & edit view. Thanks!
Okay, so here we are... I used Laravel's form model binding in the example. (I work with User model/db table).
If this topic is not clear for you, take a look at this http://laravel.com/docs/html#form-model-binding
// Controller
class UsersController extends BaseController
{
...
// Method to show 'create' form & initialize 'blank' user's object
public function create()
{
$user = new User;
return View::make('users.form', compact('user'));
}
// This method should store data sent form form (for new user)
public function store()
{
print_r(Input::all());
}
// Retrieve user's data from DB by given ID & show 'edit' form
public function edit($id)
{
$user = User::find($id);
return View::make('users.form', compact('user'));
}
// Here you should process form data for user that exists already.
// Modify/convert some input data maybe, save it then...
public function update($id)
{
$user = User::find($id);
print_r($user->toArray());
}
...
}
And here come the view file served by controller.
// The view file - self describing I think
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
#if(!$user->id)
{{ Form::model($user, ['route' => 'admin.users.store']) }}
#else
{{ Form::model($user, ['route' => ['admin.users.update', $user->id], 'method' => 'put']) }}
#endif
{{ Form::text('firstName') }}
{{ Form::text('lastName') }}
{{ Form::submit() }}
{{ Form::close() }}
</body>
</html>
Yes, let's consider the following example:
View:
{{ Form::text('title', $title) }}
Controller:
$title = 'Some default title';
if($article) {
$title = $article->title;
}
return View::make('user.login')->with('title', $title)
Then you will have a text-input with either Some default title or the title from $article, if $article isn't equal to false
All you need to do is include a conditional in your blade template.
Lets assume your database table has a field myfield, which you want to default to mydefault.
Just include the following in a partial view which is called by the create and edit views:
#if(isset($myfield))
{{ Form::input('text','myfield') }}
#else
{{ Form::input('text','myfield','mydefault') }}
#endif
You don't have to anything else.
if you mean placeholder you can do this
{{ Form::password('password', array('placeholder' => 'password'))}}
Probably easier (Laravel 5):
{{ Form::text('title', isset($yourModel) ? null : 'Some default title') }}
That is to assume you are using the form as a partial. It should populate the value if the model for the form exists (you are editing or patching record) else it should show you the default you wish.
When you are using the Schema builder (in Migrations or somewhere else):
Schema::create(
'posts', function($table) {
$table->string('title', 30)->default('New post');
}
);
If you want to do this conditionally, an alternative method of solving this could be to perform a check instead. If this check passes, set the default (as is done below with $nom as an example). Otherwise, leave it empty by setting it to null explicitly.
{{ Form::text('title', (isset($nom)) ? $nom : null) }}