symfony2 update entity out of modal - ajax

almost whole night I'm trying to update an entity with a form in a modal, but it doesn't work...
My twig template looks like :
{% for entity in entities %}
<tr>
<td class="text-center">{{ entity.id }}</td>
<td class="text-center">{{ entity.cashbackDays }} Tage</td>
<td class="text-center">{{ entity.cashbackPercent }} %</td>
<td class="text-center">{{ entity.nettoDays }} Tage</td>
<td class="text-center">
<a data-toggle="modal" data-target="#editCashbackModal" class="btn btn-xs btn-default" href="{{ path('cashback_edit', { 'id': entity.id }) }}"><i
class="fa fa-edit"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
<div class="modal fade" id="editCashBackModal" tabindex="-1" role="dialog" aria-labelledby="editCashBackModalLabel" aria-hidden="true">
</div>
the modal template looks like:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 class="modal-title" id="editCashBackModalLabel">Skontoschlüssel bearbeiten</h4>
</div>
<div class="modal-body">
{{ form(edit_form) }}
<ul class="record_actions">
<li>
<a href="{{ path('cashback') }}">
Back to the list
</a>
</li>
<li>{{ form(delete_form) }}</li>
</ul>
</div>
<div class="modal-footer">
</div>
</div>
</div>
I think I got problems with the variable in the URl but I don't know how to fix it.
This is the part of my controller:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('sulzerAppBundle:Cashback')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Cashback entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a Cashback entity.
*
* #param Cashback $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Cashback $entity)
{
$form = $this->createForm(new CashbackType(), $entity, array(
'action' => $this->generateUrl('cashback_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
The Error is that the modal doesn't open at click on edit

You have to add form submission:
protected $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('sulzerAppBundle:Cashback')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Cashback entity.');
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
$editForm->handleRequest($this->requestStack);
if ($editForm->isSubmitted() && $editForm->isValid()) {
/** #var Cashback $cashback */
$cashback = $editForm->getData();
...
$em->persist($cashback);
$em->flush();
}
...
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
Read more about forms and symfony 2.7 demo

Related

Delete method in laravel receives id parameter in null

When I want to delete a comment from a photo, the id is sent by parameter but the delete () function that deletes that record receives the same $ id as null.
First my route
Route::get('/comment/delete/{id}', [App\Http\Controllers\CommentController::class, 'delete'])->name('comment.delete');
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comments';
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function images()
{
return $this->belongsTo(Image::class, 'image_id');
}
}
CommentController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function save(Request $request){
//Validacion
$validate = $this->validate($request, [
'image_id' => 'required|integer',
'content' => 'string|required'
]);
//Recoger datos
$user = \Auth::user();
$content = $request->input('content');
$image_id = $request->input('image_id');
//Asigno los valores a mi objeto
$comment = new Comment;
$comment->user_id = $user->id;
$comment->image_id = $image_id;
$comment->content = $content;
//guardar en la base de datos
$comment->save();
return redirect()->route('image.detail', [
'id' => $image_id
])->with([
'message' => 'Haz hecho un comentario'
]);
}
public function delete($id){
//Conseguir datos del usuario identificado
$user = \Auth::user();
//Conseguir objeto del comentario
$comment = Comment::find($id);
dd($comment);
//Comprobar si soy el dueño del comentario o de la publicacion
if ($user && ($comment->users_id == $user->id || $comment->images_id->users_id == $user->id)) {
$comment->delete();
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario eliminado'
]);
}else{
return redirect()->route('image.detail', ['id' => $comment->images->id])
->with([
'message' => 'Comentario NO eliminado!'
]);
}
}
}
View:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
#include('includes.message')
<div class="card pub_image pub_image_detail">
<div class="card-header">
#if($image->user->image)
<div class="container-avatar">
<img src="{{route('user.avatar', ['filename' => $image->user->image])}}" class="avatar">
</div>
#endif
<div class="data-user">
{{$image->user->name.' '.$image->user->surname}}
<span class="nickname">
{{' | #'.$image->user->nick}}
</span>
</div>
</div>
<div class="card-body">
<div class="image-container">
<img src="{{ route('image.file', ['filename' => $image->imagen_path]) }}" alt=""/>
</div>
<div class="description">
<span class="nickname">{{'#'.$image->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($image->created_at)}}</span>
<p>{{$image->description}}</p>
</div>
<div class="likes">
<img src="{{asset('/img/corazon-negro.png')}}" alt=""/>
</div>
<div class="clearfix"></div>
<div class="comments">
<h4>Comentarios ({{count($image->comments)}})</h4>
<hr>
<form action="{{route('comment.save')}}" method="POST">
#csrf
<input type="hidden" name="image_id" value="{{$image->id}}">
<p>
<textarea name="content" id="" cols="30" rows="10" class="form-control box-comment {{$errors->has('content') ? 'is-invalid' : ''}}"></textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</p>
<button type="submit" class="btn btn-success">
Enviar
</button>
</form>
#foreach($image->comments as $comment)
<div class="comment">
<span class="nickname">{{'#'.$comment->user->nick}}</span>
<span class="nickname date">{{' | '.\FormatTime::LongTimeFilter($comment->created_at)}}</span>
<p>{{$comment->content}}</p>
#if(Auth::check() && ($comment->user->id == Auth::user()->id || $comment->images->users_id == Auth::user()->id))
<a href="{{route('comment.delete', ['id', $comment->id])}}" class="btn btn-sm btn-danger">
Eliminar
</a>
#endif
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
I would like to know how I can make the delete button correctly send the id by parameter to the controller, that it receives it and then removes the comment.
Thanks!
Your issue is not defining the id correctly in the array :
{{ route('comment.delete', ['id', $comment->id]) }}
It should be like this:
{{ route('comment.delete', ['id' => $comment->id]) }}

How to add action columns in yajra datatables laravel

im stuck adding column actions for edit and delete button with yajra datatables, im using DataTables Service because im wanna add export button too, here is my my datatables code :
public function dataTable($query)
{
return datatables()
->eloquent($query);
}
/**
* Get query source of dataTable.
*
* #param \App\InfoDataTable $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(InfoDataTable $model)
{
// return $model->newQuery();
$data = DataInfo::select('data-info.*');
return $this->applyScopes($data);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->addAction()
->parameters([
'dom' => 'Bfrtip',
'buttons' => ['csv', 'excel', 'print'],
]);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
Column::make('employee_no'),
Column::make('name'),
Column::make('address'),
Column::make('birthplace'),
Column::make('birthdate'),
Column::make('age'),
Column::make('occupation'),
Column::make('status'),
Column::make('gender'),
Column::make('startdate'),
];
}
and here is my code in my controller for rendering the table
public function index(InfoDataTable $dataTable)
{
$User = User::where('id', Auth::id())->first();
if($User->role == 'superadmin'){
return $dataTable->render('superadmin.index');
} else {
return $dataTable->render('admin.index');
}
}
and my blade looks like this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
<div class="card-body">
<div class="table-responsive">
<div class="panel panel-default">
{{(!! $dataTable->table() !!)}}
</div>
</div>
</div>
</div>
</div>
</div>
#stop
#push('scripts')
{!! $dataTable->scripts() !!}
#endpush
my current view looks like this
any suggestions? sorry for my broken english, tried many tutorial but can't find the correct one
Actions column is default for yajra datatables. So I found how to remove it: https://yajrabox.com/docs/laravel-datatables/6.0/remove-column (I have never tried this)
public function dataTable($query)
{
return datatables()
->eloquent($query)
->removeColumn('action');
}
If you want to edit actions column, try my code:
public function dataTable($query)
{
$dataTable = new EloquentDataTable($query);
return $dataTable->addColumn('action', 'folderNameInViewfolder.datatables_actions');
}
This is what in datatables_actions (full name: datatables_actions.blade.php)
{!! Form::open(['route' => ['routename.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
<a href="{{ route('routename.show', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-eye-open"></i>
</a>
<a href="{{ route('routename.edit', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-edit"></i>
</a>
{!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
'type' => 'submit',
'class' => 'btn btn-danger btn-xs',
'onclick' => "return confirm('Are you sure?')"
]) !!}
</div>
{!! Form::close() !!}
My code is different from yours, so I will show my code:
Datatables code:
public function dataTable($query)
{
$dataTable = new EloquentDataTable($query);
return $dataTable->addColumn('action', 'cachthuclamviecs.datatables_actions');
}
/**
* Get query source of dataTable.
*
* #param \App\Models\Cachthuclamviec $model
* #return \Illuminate\Database\Eloquent\Builder
*/
public function query(Cachthuclamviec $model)
{
return $model->newQuery();
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->columns($this->getColumns())
->minifiedAjax()
->addAction(['width' => '120px', 'printable' => false])
->parameters([
'dom' => 'Bfrtip',
'stateSave' => true,
'order' => [[0, 'desc']],
'buttons' => [
['extend' => 'create', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-plus"></i> Thêm</span>'],
['extend' => 'export', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-download"></i> Xuất <span class="caret"></span></span>'],
['extend' => 'print', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-print"></i> In</span>'],
['extend' => 'reset', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-undo"></i> Cài lại</span>'],
['extend' => 'reload', 'className' => 'btn btn-default btn-sm no-corner', 'text' => '<span><i class="fa fa-refresh"></i> Tải lại</span>'],
],
]);
}
/**
* Get columns.
*
* #return array
*/
protected function getColumns()
{
return [
'cachthuclamviec'
];
}
Controller code:
public function index(CachthuclamviecDataTable $cachthuclamviecDataTable)
{
return $cachthuclamviecDataTable->render('cachthuclamviecs.index');
}
Blade code:
#section('css')
#include('layouts.datatables_css')
#endsection
{!! $dataTable->table(['width' => '100%', 'class' => 'table table-striped table-bordered']) !!}
#push('scripts')
#include('layouts.datatables_js')
{!! $dataTable->scripts() !!}
#endpush
datatables_actions blade code:
{!! Form::open(['route' => ['cachthuclamviecs.destroy', $id], 'method' => 'delete']) !!}
<div class='btn-group'>
<a href="{{ route('cachthuclamviecs.show', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-eye-open"></i>
</a>
<a href="{{ route('cachthuclamviecs.edit', $id) }}" class='btn btn-default btn-xs'>
<i class="glyphicon glyphicon-edit"></i>
</a>
{!! Form::button('<i class="glyphicon glyphicon-trash"></i>', [
'type' => 'submit',
'class' => 'btn btn-danger btn-xs',
'onclick' => "return confirm('Are you sure?')"
]) !!}
</div>
{!! Form::close() !!}
Put file datatables_actions here: datatables_actions:
Code maybe have differences because of Boostrap, jQuery,... version

Sorting and searching a foreign entity field on a Laravel Livewire table

I’ve just implemented a Livewire data table based on the Caleb’s tutorial on Laracasts. Everything works as expected when working with just one model. However I’m stuck trying to apply sorting and searching to a foreign model field.
User model:
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user's email verified status.
*
* #param string $value
* #return string
*/
public function getEmailVerifiedAtAttribute($value)
{
if ($value == null) {
return "No";
}
return $value;
}
public function getRoleAttribute()
{
if($this->roles()->count() > 0) {
return $this->roles()->first()->name;
} else {
return "Usuario registrado";
}
}
public static function search($query)
{
return empty($query) ? static::query()
: static::where('name', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%');
}
}
Tried adding another orWhere() clause to the search() method in some ways. None worked. Now I left just the default ones.
Livewire controller:
namespace App\Http\Livewire\Users;
use Livewire\Component;
use Livewire\WithPagination;
class Table extends Component
{
use WithPagination;
public $perPage;
public $sortField;
public $sortAsc;
public $search;
public function mount()
{
$this->perPage = 10;
$this->sortField = 'name';
$this->sortAsc = true;
$this->search = '';
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
return view('livewire.users.table', [
'users' => \App\User::search($this->search)
->with('roles')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage),
]);
}
}
Livewire view:
<div>
<div class="row mb-4">
<div class="col form-inline">
Mostrar
<select wire:model="perPage" class="form-control form-control-sm custom-select custom-select-sm">
<option>10</option>
<option>100</option>
<option>1000</option>
</select>
registros
</div>
<div class="col-sm-3">
<input wire:model="search" class="form-control form-control-sm" type="text" placeholder="Buscar usuarios...">
</div>
</div>
<div class="table-responsive mb-4" >
<div class="table-header">
<table class="table table-sm text-nowrap" role="grid">
<thead>
<tr>
<th width="30%">
<a wire:click.prevent="sortBy('name')" role="button" href="#">
Nombre
#include('partials._sort-icon', ['field' => 'name'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('email')" role="button" href="#">
Correo electrónico
#include('partials._sort-icon', ['field' => 'email'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('')" role="button" href="#">
Rol
#include('partials._sort-icon', ['field' => ''])
</a>
</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table class="table table-sm table-hover text-nowrap" role="grid">
<tbody>
#foreach ($users as $user)
<tr>
<td width="30%">{{ $user->name }}</td>
<td width="30%">{{ $user->email }}</td>
<td width="30%">{{ $user->role }}</td>
<td>
<form method="POST" action="{!! route('backend.users.user.destroy', $user->id) !!}" accept-charset="UTF-8">
<input name="_method" value="DELETE" type="hidden">
{{ csrf_field() }}
<div class="btn-group btn-group-xs float-right" role="group">
#can('users.show')
<a href="{{ route('backend.users.user.show', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.show') }}">
<i class=" fas fa-fw fa-eye" aria-hidden="true"></i>
</a>
#endcan
#can('users.edit')
<a href="{{ route('backend.users.user.edit', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.edit') }}">
<i class=" fas fa-fw fa-pencil-alt" aria-hidden="true"></i>
</a>
#endcan
#can('users.destroy')
<button type="submit" class="btn btn-outline-default btn-xs" title="{{ trans('users.delete') }}" onclick="return confirm("{{ trans('users.confirm_delete') }}")">
<i class=" fas fa-fw fa-trash-alt" aria-hidden="true"></i>
</button>
#endcan
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="table-footer">
<div class="text-muted">
Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} out of {{ $users->total() }} results
</div>
<div>
{{ $users->links() }}
</div>
</div>
</div>
Tried also some ways to pass an argument to the sortBy() and [‘field’ => ‘’] on the role column. Now I left them with empty strings.
I know, this issue probably is more related to Laravel than Livewire, but I’ll really appreciate any help.
Update:
Solved using the Laravel Query Builder instead of Eloquent.

Unable to show data from database in Laravel after inserting data into database

I was able to insert data into database in Laravel but when I was trying to show the data in a tabular form I couldn't - it was displaying Route [stock_edit] not defined. (View: C:\wamp\www\pump\core\resources\views\dashboard\stock-show.blade.php)
Like I said in my quetion yesterday, I am new to Laravel and I am yet to understand the environment. I have been on this for the past 48 hours searching for help online but couldn't find a satisfactory ones
Here is my stock-show.blade.php
#extends('layouts.dashboard')
#section('title', 'All Stock')
#section('content')
#if(count($stock))
<div class="row">
<div class="col-md-12">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>ID#</th>
<th>Product Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($stock as $p)
<tr>
<td>{{ $p->id }}</td>
<td>{{ $p->name }}</td>
<td>{{ $p->price }} </td>
<td>
<i class="fa fa-edit"></i> EDIT
<button type="button" class="btn btn-danger btn-sm delete_button"
data-toggle="modal" data-target="#DelModal"
data-id="{{ $p->id }}">
<i class='fa fa-times'></i> DELETE
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div><!-- ROW-->
<div class="text-center">
{!! $stock->render() !!}
</div>
#else
<div class="text-center">
<h3>No Data available</h3>
</div>
#endif
<!-- Modal for DELETE -->
<div class="modal fade" id="DelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"> <i class='fa fa-trash'></i> Delete !</h4>
</div>
<div class="modal-body">
<strong>Are you sure you want to Delete ?</strong>
</div>
<div class="modal-footer">
<form method="post" action="{{ route('stock_delete') }}" class="form-inline">
{!! csrf_field() !!}
{{ method_field('DELETE') }}
<input type="hidden" name="id" class="abir_id" value="0">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">DELETE</button>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function () {
$(document).on("click", '.delete_button', function (e) {
var id = $(this).data('id');
$(".abir_id").val(id);
});
});
</script>
#endsection
and this is the DashboardController.php
//Stocks
public function createStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "Create Stock";
//$data['currency'] = Currency::all();
return view('dashboard.stock-create',$data);
}
public function storeStock(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:stocks,name',
'price' => 'required',
//'currency_id' => 'required'
]);
try {
$stock = Input::except('_method','_token');
Stock::create($stock);
session()->flash('message', 'Stock Create Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}
public function showStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "All Stock";
$data['stock'] = Stock::orderBy('id','ASC')->paginate(100);
return view('dashboard.stock-show',$data);
}
public function editStock($id)
{
$data['stock'] = Stock::findOrFail($id);
$data['site_title'] = $this->site_title;
$data['page_title'] = 'Edit Product';
$data['stock'] = Stock::all();
return view('dashboard.stock-edit',$data);
}
public function updateStock(Request $request,$id)
{
$stocks = Stock::findOrFail($id);
$this->validate($request,[
'name' => 'required|unique:stocks,name,'.$stocks->id,
'price' => 'required',
//'currency_id' => 'required',
]);
try {
$stock = Input::except('_method','_token');
$stocks->fill($stock)->save();
session()->flash('message', 'Stock Updated Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}//Stocks End
And lastly the route.php
/* Stock Route List */
Route::get('stock-create',['as'=>'stock-create','uses'=>'DashboardController#createStock']);
Route::post('stock-create',['as'=>'stock-store','uses'=>'DashboardController#storeStock']);
Route::get('stock-show',['as'=>'stock-show','uses'=>'DashboardController#showStock']);
Route::get('stock-edit/{id}',['as'=>'stock-edit','uses'=>'DashboardController#editStock']);
Route::put('stock-edit/{id}',['as'=>'stock-update','uses'=>'DashboardController#updateStock']);
You have a typo in your code,
change stock_edit to stock-edit in your view

Creating a task with the task list id as foreign

I've created a task list which displays several tasks. I can create lists in my page and the task itself, but, I'm receiving an error on the constraint as it has to come with the ID of the task that it's being created.
Currently the task is created under a loop in the view on laravel 4 (tasks/index.blade.php).
#foreach ($tasks_lists as $task_list)
<div class="col-lg-3 col-md-4 container_tasks">
<h4>{{ $task_list->title }} <small>(Nueva tarea)</small><button class="close" type="button" data-toggle="modal" data-target=".delete-task-list-modal{{ $task_list->id }}">×</button></h4>
<ul>
#foreach ($task_list->tasks as $task)
<li>
{{ Form::open(array('url' => 'tareas.marcar', 'class' => 'createTaskList')) }}
<input
type="checkbox"
onclick="this.form.submit()"`
{{ $task->done ? 'checked' : '' }}
/>
<input type="hidden" name="id" value="{{ $task->id }}" />
{{ $task->name }}
{{ Form::close() }}
</li>
#endforeach
</ul>
</div>
<div class="modal fade create-task-modal{{ $task_list->id }}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Crear lista de tareas</h4>
</div>
<div class="modal-body">
{{ Form::open(array('url' => 'tareas', 'class' => 'createTask')) }}
<div class="form-group">
{{ Form::label('name', 'Nombre') }}
{{ Form::text('name', Input::old('name'), array('class' => 'form-control')) }}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
{{ Form::submit('Crear tarea', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
And this is my controller (TaskController.php):
public function store()
{
$task_list =
// Reglas de validación
$rules = array(
'name' => 'required|min:3|max:30'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('tareas')
->withErrors($validator)
->with('notice_type', 'danger')
->with('notice', 'Los siguientes errores ocurrieron:')
->withInput();
} else {
// store
$task = new Task;
$task->name = Input::get('name');
$task->save();
return Redirect::to('tareas')
->with('notice_type', 'success')
->with('notice', 'La tarea ha sido agregado satisfactoriamente.');
}
}
How would I go about adding the ID of the current task list when creating the task, so that the task is added properly to its list when clicking the .create-task-modal
Lucus
The easist way would be to add a hidden field after
{{ Form::open(array('url' => 'tareas', 'class' => 'createTask')) }}
so it's like
{{ Form::open(array('url' => 'tareas', 'class' => 'createTask')) }}
{{ Form::hidden('task_list_id', $task_list->id) }}
then, in your controller do
$rules = array(
'task_list_id' => 'required|exists:task_lists,id', //check the docs for exists
'name' => 'required|min:3|max:30'
);
...
// option 1
$task = new Task;
$task->task_list_id = Input::get('task_list_id');
$task->name = Input::get('name');
$task->save();
// option 2 (depending on your fillable
$task = new Task(Input::only('task_list_id', 'name');
$task->save();

Resources