I make a clone system in Laravel. I want to clone activities.
When I click on "Clone", my line is cloned and receives as the value in the column "parent_id" the ID of the original.
The original gets a value of 1 in the "hasClone" column.
But when I want to delete a clone, in my destroy method, I try to set hasClone (the original entry) to NULL before deleting the clone.
Here is my code :
public function destroyChanges(Activity $activity)
{
$parentActivity = Activity::findOrFail($activity->parent_id)->first();
$parentActivity->hasClone = NULL;
$parentActivity->save();
$activity->delete();
return redirect()->to('/admin/activity/');
}
Here is my route :
Route::delete('activity/destroyChanges/{id}', ['as' => 'cancel.activity', 'uses' => 'ActivityCrudController#destroyChanges']);
Here is my button :
{{ Form::open([ 'method' => 'DELETE', 'route' => [ 'cancel.activity', $entry->getKey() ] ]) }}
<button class="btn btn-default"><i class="fa fa-ban"></i> {{ trans('backpack::crud.cancel') }}</button>
{{ Form::close() }}
The entry of the clone is deleted correctly. But he does not update the original entry. How to do ? thank you very much
EDIT : I also tried that :
public function destroyChanges($id)
{
$activity = Activity::findOrFail($id);
$parentActivity = Activity::where('id', '=', $activity->parent_id)->first();
$parentActivity->hasClone = NULL;
$parentActivity->save();
$activity->delete();
return redirect()->to('/admin/activity/');
}
Even if I put a die (); in the destroy method, he ignores it. Why does not it take it into account?
You need to define parent method in your model and access the parent like the best answer in the following toppic:
How to implement a self referencing (parent_id) model in Eloquent Orm
when you access to that can change hasClone field and save that before the update.
Like this:
$parentActivity = $activity->parent()->first();
$parentActivity->hasClone = null;
$parentActivity->save();
Ensure to have something like this in your activity model:
public function parent()
{
return $this->belongsTo('Activity', 'parent_id');
}
Related
I have a User and a Tag model. Both are linked by a 1:N relation.
I am trying to take col tag_name from user model. However I am receiving this error:
Trying to get Trying to get property 'tag_name' of non-object.
User model has
// linking with table tag
public function tags(){
return $this->hasMany('App\Tag');
}
Tag model has
public function user(){
return $this->belongsTo('App\User', 'user_id');
}
My view has
{{ Form::checkbox('tag[]',$user->tag_id,['class'=>'cats']) }}
{{ Form::label('tb',$user->tag_id->tag_name,['class'=>'btn btncategory']) }}
Controller has the following in index function
$user = User::find($user_id);
return view('user.create_post')->with('user', $user );
Route:
Route::get('create', 'PostsController#index');
Please help me where I am wrong.
Thanks in advance.
The problem is that your user has multiple tags you need to loop through each of them:
In blade file:
#foreach ($user->tags as $tag)
<label class="btn btncategory">
<input type="checkbox" name=tag[] value="{{$tag->id}}" class="cats" />
{{$tag->name}}
</label>
#endforeach
Now when you submit this you should have all checked tags in the array request()->input('tag')
Note I've removed the Form:: because I like to put the checkboxes inside the label but you can just use the Form:: style if you want like below:
#foreach ($user->tags as $tag)
{{ Form::checkbox('tag[]',$tag->id,['class' => 'cats']) }}
{{ Form::label('tb',$tag->name,['class' => 'btn btncategory']) }}
#endforeach
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);
}
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
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) }}