Multiple forms in one view Laravel 5.1 - forms
I have a problem. Someone could tell me can i use couple forms in one vie on one route? I mean i have three forms with post method in show.blade.php in show function in ProfileController which showing users profiles. I posting 3 forms in this view,and in route i have something like this:
Route::post('profile/{id}', MessageController#store');// this is private message to other user
Route::post('profile/{id}', CommentController#store'); //this is comment to profile
Route::post('profile/{id}', CommentController#storeCommit'); // this is answer to comment profile
I dont know what i doing wrog,but this isdont work,i mean if i delete CommitStore route i can send message and add comment,but if i add this storeCommit i cant add comment,because i getting error, field from storeCommit cannot be null. Tomorrow i add code from controllers and view. Someone have any idea, please, help me, thanks.
This is View which has three forms, Sending Messages, Adding Comment to Profile and Adding Answer to Comment in profile:
#extends('layout')
#section('content')
<div>
<!-- Nav tabs -->
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">Informacje</li>
<li role="presentation">Postacie</li>
<li role="presentation">Posty</li>
<li role="presentation">Komentarze</li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="info">
<table class="table table-bordered">
<tr class="active">
<td> Avatar </td>
<td> Informacje </td>
</tr>
<tr class="info">
<td>
<img src="{{$user->avatar}}" width="150px" height="150px" alt="Avatar" class="img-circle"> <BR /><BR />
#if(!\Auth::guest() && $user->id == \Auth::user()->id)
<a style="text-align:right" href="/profile/{{$user->id}}/edit"<button type="button" class="btn btn-primary btn-xs">Edytuj profil</button></a>
#endif
#if(!\Auth::guest() && \Auth::id() != $user->id)
<button style="float:right" type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal">
<span class="glyphicon glyphicon-pencil"></span>
</button>
#endif
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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="myModalLabel">Wyślij wiadomość do {{$user->name}}</h4>
</div>
<div class="modal-body">
{!! Form::model(['method' => 'POST', 'action' => ['MessageController#store', $user->id]]) !!}
<div class="form-group">
{!! Form::text('title', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź tytuł wiadomości' ]) !!}
</div>
<div class="form-group">
{!! Form::textarea('message', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź wiadomość' ]) !!}
</div>
{!! Form::hidden('mess_to_user', $user->id) !!}
{!! Form::hidden('from_user_name', $user->name) !!}
</div>
<div class="modal-footer">
{!! Form::submit('Wyślij wiadomość', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
</div>
</td>
<td width="960">
{!!$user->showName($user->name)!!}
#if($user->is_online == 1)
<span class="label label-success">Online</span>
#else
<span class="label label-danger">Offline</span>
#endif
<BR />
#foreach($user->group as $group)
<strong>Grupa użytkownika:</strong> {{$group->name}}
#endforeach
<BR />
<strong>Dołączył dnia:</strong> {{$user->created_at->diffForHumans()}} <BR />
<strong>Wiek: </strong>{{$user->age}}
<strong>Płeć: </strong>{{$user->formatSex($user->sex)}} <BR />
<div class="panel panel-primary">
<div class="panel-heading" role="tab" id="headingTwo">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Sygnatura użytkownika {{$user->name}}
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
<div class="panel-body">
#if(empty($user->signature))
Brak sygnatury
#else
{!! $user->signature !!}
#endif
</div>
</div>
</div>
</td>
</tr>
</table>
<table class="table table-condensed">
<!-- Tabela na KONTAKTY-->
<tr>
<!--SOCIAL-->
<td>
<table class="table table-condensed">
<tr>
<td class="active">
#if(empty($user->skype))
<img src="http://a3.mzstatic.com/eu/r30/Purple6/v4/1e/0c/96/1e0c9683-1019-f450-f07e-017b6f0012c6/icon175x175.png" width="16" height="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://a3.mzstatic.com/eu/r30/Purple6/v4/1e/0c/96/1e0c9683-1019-f450-f07e-017b6f0012c6/icon175x175.png" width="16" height="16" /> {{$user->skype}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->facebook))
<img src="http://blogs-images.forbes.com/peterhimler/files/2014/02/high-res-logo_facebook1.png" width="16" height="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://blogs-images.forbes.com/peterhimler/files/2014/02/high-res-logo_facebook1.png" width="16" height="16" /> {{$user->facebook}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->twitter))
<img src="http://health.uri.edu/files/twitter.png" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://health.uri.edu/files/twitter.png" height="16" width="16" /> {{$user->twitter}}
#endif
</td>
</tr>
</table>
</td>
<!--GAME-->
<td width="50%">
<table class="table table-condensed">
<tr>
<td class="active">
#if(empty($user->xfire))
<img src="http://img06.deviantart.net/ebd6/i/2008/045/6/3/xfire_enhanced_icon_by_sparticusx.jpg" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://img06.deviantart.net/ebd6/i/2008/045/6/3/xfire_enhanced_icon_by_sparticusx.jpg" height="16" width="16" /> {{$user->xfire}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->steam))
<img src="http://vignette3.wikia.nocookie.net/clickerheroes/images/5/54/Logo-Steam.png/revision/latest?cb=20150529052012" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="http://vignette3.wikia.nocookie.net/clickerheroes/images/5/54/Logo-Steam.png/revision/latest?cb=20150529052012" height="16" width="16" /> {{$user->steam}}
#endif
</td>
</tr>
<tr>
<td class="active">
#if(empty($user->origin))
<img src="https://pbs.twimg.com/profile_images/525760420192083969/Tv_fRfVF_400x400.png" height="16" width="16" /> <span class="label label-warning">Niezdefiniowano</span>
#else
<img src="https://pbs.twimg.com/profile_images/525760420192083969/Tv_fRfVF_400x400.png" height="16" width="16" /> {{$user->origin}}
#endif
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="postacie">
<table class="table table-bordered">
<tr class="active">
<td>
#forelse($user->player as $player)
<button type="button" style="width:200px; height:200px" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal{{$player->id}}">{!!$player->checkActive($player->active)!!}<BR />{!! Html::image('skin/Skin_'.$player->skin.'.png') !!}<BR/>
{{$player->formatName($player->name)}} </button>
#empty
#if(!\Auth::guest() && $user->id == \Auth::user()->id)
<center><p><h1><span class="glyphicon glyphicon-plus-sign"></span></h1></p></center>
#else
<center><h1><span class="label label-default">Brak postaci!</span></h1></center>
#endif
#endforelse
</td>
</tr>
</table>
</div>
<div role="tabpanel" class="tab-pane" id="posty">...</div>
<div role="tabpanel" class="tab-pane" id="komentarze">
<BR />
#if(!\Auth::guest())
<div class="panel panel-warning">
<div class="panel-heading">
Dodaj komentarz do profilu użytkownika {!!$user->showName($user->name)!!}
</div>
<div class="panel-body">
{!! Form::model(['method' => 'POST', 'action' => ['CommentController#store', $user->id]]) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź komentarz do tego profilu ' ]) !!}
</div>
{!! Form::hidden('to_user', $user->id) !!}
<div class="form-group">
{!! Form::submit('Dodaj komentarz', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
#endif
#forelse($user->queryComment($comments, $user->id) as $com)
<div class="panel panel-primary">
<div class="panel-heading">
Komentarz od <a style="color:white" href="/profile/{{$com->user_id}}">{{$com->name}}</a> <span class="label label-warning">{{$com->created_at}}</span>
#if(!\Auth::guest())
<button style="float:right" type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal{{$com->id}}">
<span class="glyphicon glyphicon-plus-sign"></span>
</button>
#endif
</div>
<div class="panel-body">
{{$com->comment}}
</div>
<div class="panel panel-success">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{$com->id}}" aria-expanded="false" aria-controls="collapseOne">
Pokaż wszystkie komentarze
</a>
</h4>
</div>
<div id="collapse{{$com->id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
#forelse($user->queryCommit($commits, $com->id) as $commit)
<div class="panel-body">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">Podkomentarz od {{$commit->user_name}} <span class="label label-warning">{{$commit->created_at}}</span> </h3>
</div>
<div class="panel-body">
{{$commit->body}}
</div>
</div>
</div>
#empty
<div class="panel-body">
Brak podkomentarzy!
</div>
#endforelse
</div>
</div>
<div class="modal fade" id="myModal{{$com->id}}" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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="myModalLabel">Dodaj komentarz</h4>
</div>
<div class="modal-body">
{!! Form::model(['method' => 'POST', 'action' => ['CommentController#storeCommit', $user->id]]) !!}
<div class="form-group">
{!! Form::text('body', null, ['class' => 'form-control', 'placeholder' => 'Wprowadź adnotację do wybranego komentarza ' ]) !!}
</div>
{!! Form::hidden('to_comment', $com->id) !!}
{!! Form::hidden('to_user_com_id', $user->id) !!}
</div>
<div class="modal-footer">
{!! Form::submit('Dodaj komentarz', ['class' => 'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
#include('errors.list')
</div>
</div>
</div>
</div>
#empty
<p>Brak komentarzy w profilu</p>
#endforelse
{!!$comments->render()!!}
</div>
#include('errors.list')
#foreach($user->player as $p)
#include('character.show')
#endforeach
</div>
#stop
This is MessageController and CommentController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\CommentRequest;
use App\Http\Requests\CommitRequest;
use App\Comment;
use App\Commit;
class CommentController extends Controller
{
public function store(CommentRequest $request)
{
\Auth::user()->comment()->create([
'comment' => $request->input('comment'),
'to_user' => $request->input('to_user'),
'from_name' => \Auth::user()->name
]);
flash()->success('Komentarz został dodany!');
return redirect('/profile/'.$request->input('to_user').'');
}
public function storeCommit(CommitRequest $request)
{
Commit::create(
[
'body' => $request->input('body'),
'to_comment' => $request->input('to_comment'),
'user_name' => \Auth::user()->name,
'from_user_id' => \Auth::id(),
'to_user_com_id' => $request->input('to_user_com_id')
]);
flash()->success('Dodałeś adnotację do komentarza!');
return redirect('/profile');
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Requests\MessageRequest;
use App\Http\Requests\AnswerRequest;
use App\Message;
use App\User;
use App\Answer;
class MessageController extends Controller
{
public function __construct()
{
parent::__construct();
$this->middleware('auth');
}
public function index()
{
$sent = Message::where('from_user', \Auth::id())->count();
$got = Message::where('to_user', \Auth::id())->count();
$read = Message::where('to_user', \Auth::id())->where('read', 1)->count();
$notread = Message::where('to_user', \Auth::id())->where('read', 0)->count();
$sentto = Message::where('from_user', \Auth::id())->latest('created_at')->take(1)->get();
$gotfrom = Message::where('to_user', \Auth::id())->latest('created_at')->take(1)->get();
return view('message.index', compact('sent', 'got', 'sentto', 'gotfrom', 'read', 'notread'));
}
public function store(MessageRequest $request)
{
\Auth::user()->message()->create([
'title' => $request->input('title'),
'message' => $request->input('message'),
'to_user_id' => $request->input('mess_to_user'),
'from_user_name' => \Auth::user()->name,
'to_user_name' => $request->input('from_user_name')
]);
flash()->success('Udało Ci się wysłać prywatną wiadomość!');
return redirect('/profile/'.$request->input('mess_to_user').'');
}
public function show($id)
{
$message = Message::findOrFail($id);
$answers = Answer::paginate(10);
if($message->to_user == \Auth::id() || $message->from_user == \Auth::id())
{
if($message->to_user == \Auth::id())
{
Message::where('id', $id)->update(['read' => 1]);
}
return view('message.show', compact('message', 'answers', 'check'));
}
else
{
return back();
}
}
public function got()
{
$messages = Message::where('to_user', \Auth::id())->latest('created_at')->paginate(10);
return view('message.got', compact('messages'));
}
public function sent()
{
$messages = Message::where('from_user', \Auth::id())->latest('created_at')->paginate(10);
return view('message.sent', compact('messages'));
}
public function storeAnswer(AnswerRequest $request)
{
Answer::create([
'answer' => $request->input('answer'),
'user_id' => \Auth::id(),
'user_name' => \Auth::user()->name,
'to_message' => $request->input('to_message')
]);
flash()->success('Wiadomość prywatna została wysłana!');
return redirect('/private/'.$request->input('to_message').'');
}
}
Route.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/*==========This is main controller=============*/
Route::get('/', 'Controller#index');
Route::get('about', 'Controller#about');
Route::get('contact', 'Controller#contact');
Route::get('teammate', 'Controller#teammate');
/*=========Questions Controll===================*/
Route::get('quest', 'QuestController#index');
Route::get('quest/create', 'QuestController#create');
Route::get('quest/{id}', 'QuestController#show');
Route::post('quest', 'QuestController#store');
/*=============Changelog controller==============*/
Route::get('change/create', 'ChangeController#create');
Route::get('change', 'ChangeController#index');
Route::post('change', 'ChangeController#store');
/*=============Admin Controller==================*/
Route::get('admin', 'AdminController#index');
Route::get('admin/group/create', 'AdminController#createGroup');
Route::post('admin/group', 'AdminController#storeGroup');
Route::get('admin/note/create', 'AdminController#createNote');
Route::post('admin/note', 'AdminController#storeNote');
Route::get('admin/section/create', 'AdminController#createSection');
Route::post('admin/section', 'AdminController#storeSection');
Route::get('admin/article/create', 'AdminController#createArticle');
Route::post('admin/article', 'AdminController#storeArticle');
Route::get('admin/article/{id}', 'AdminController#showArticle');
Route::get('admin/article/{id}/edit', 'AdminController#editArticle');
Route::post('admin/article/{id}', 'AdminController#updateArticle');
Route::get('admin/profile', 'AdminController#profile');
Route::get('admin/profile/{id}/edit', 'AdminController#editProfile');
Route::post('admin/profile/{id}', 'AdminController#updateProfile');
/*=============Profile Controller================*/
Route::get('profile', 'ProfileController#index');
Route::get('profile/{id}', 'ProfileController#show');
Route::get('profile/{id}/edit', 'ProfileController#edit');
Route::post('profile/{id}', 'ProfileController#update');
Route::post('profile/{id}, 'MessageController#store');
Route::post('profile/{id}, 'CommentController#store');
/*============Character Controller===============*/
Route::get('character/create', 'CharacterController#create');
Route::post('character', 'CharacterController#store');
Route::get('character/online', 'CharacterController#online');
/*============Private Message Controller==========*/
Route::get('private', 'MessageController#index');
Route::get('private/got', 'MessageController#got');
Route::get('private/sent', 'MessageController#sent');
Route::get('private/{id}', 'MessageController#show');
Route::post('private/{id}', 'MessageController#storeAnswer');
Route::controllers(
[
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
You are using the same route to access two different functions. That is why when you delete one the code works.
//This is wrong.
Route::post('profile/{id}', CommentController#store');
Route::post('profile/{id}', CommentController#storeCommit');
You can either mention one as "get" and other as "post" and make the required changes within the respective function to fetch and process data.
Route::get('profile/{id}', CommentController#store');
Route::post('profile/{id}', CommentController#storeCommit');
Else, give two different routes for the functions
Route::post('profile/{id}', CommentController#store');
Route::post('profile/storeCommit/{id}', CommentController#storeCommit');
Updated
Try changing the third form like this:
{!! Form::open(array('method'=>'post', 'route' => array('store.commit', $object->id))) !!}
And change your route like this:
Route::post('profile/storeCommit/{id}', ['uses' => 'CommentController#storeCommit', 'as' => 'store.commit']);
Hope this is helpful.
Related
Codeigniter Cannot submit an ip adres on a form. Throws a Forbidden error
Here is my html form. <?php echo form_open(base_url('admin/subeler/add'), 'class="form-horizontal"'); ?> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="grup">Grup Adı</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="grup" required name="grup" value="<?php echo set_value('grup'); ?>" class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="name">Şube Adı</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="name" required name="name" value="<?php echo set_value('name'); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="ip">İp Adresi</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="ip" required name="ip" value="<?php echo set_value("ip"); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="path">Database Adı</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="path" required name="path" value="<?php echo set_value('path'); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="lisans">Lisans Tarihi</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="lisans" required name="lisans" value="<?php echo set_value('lisans'); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="il">İl</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="il" name="il" value="<?php echo set_value('il'); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="ilce">İlçe</label> </div> <div class="col-lg-8 col-md-10 col-sm-8 col-xs-7"> <div class="form-group"> <div class="form-line"> <input type="text" id="ilce" name="ilce" value="<?php echo set_value('ilce'); ?>"class="form-control"> </div> </div> </div> </div> <div class="row clearfix"> <div class="col-lg-offset-2 col-md-offset-2 col-sm-offset-4 col-xs-offset-5"> <input type="submit" name="submit" value="EKLE" class="btn btn-success m-t-15 waves-effect"> </div> </div> <?php echo form_close();?> When I enter an ip adres to the input field like (http://xxx.xxx.xx.xx:xx/) redirect me to the 403 Forbidden page but when I put " (like "http://xxx.xxx.xx.xx:xx") to the ip adres it work fine. I tried to disable xss-filter disable in config files but result is same. Can anyone give some advice. How to submit an ip adres correctly with Codeigniter? Server-Side public function add() { if ($this->input->post("submit")) { $this->form_validation->set_rules('grup', 'Grup Adı', 'trim|required'); $this->form_validation->set_rules('name', 'Şube Adı', 'trim|required'); $this->form_validation->set_rules('ip', 'İp Adresi', 'trim|required'); $this->form_validation->set_rules('path', 'Database Yolu', 'trim|required'); $this->form_validation->set_rules('lisans', 'Lisans Tarihi', 'trim|required'); if ($this->form_validation->run() == true) { $data = array( 'name' => $this->input->post('name'), 'marka' => $this->input->post('grup'), 'ip' => $this->input->post('ip'), 'il' => $this->input->post('il'), 'ilce' => $this->input->post('ilce'), 'databasePath' => $this->input->post('path'), 'lisanse_date'=>$this->input->post('lisans') ); $data = $this->security->xss_clean($data); $result = $this->sube_model->add_sube($data); if ($result) { $this->session->set_flashdata('msg', 'Şube başarılı bir şekilde eklendi!'); redirect(base_url('admin/subeler')); } } else { $data['view'] = 'admin/subeler/sube_ekle'; $this->load->view('layout', $data); } } else { $data['view'] = 'admin/subeler/sube_ekle'; $this->load->view('layout', $data); } }
Unfortunately I could not test the code exactly as provided as I don't make use of CodeIgniter 3 anymore, so I translated it into CodeIgniter 4. Also, I could not test what $this->sube_model->add_sube does. This, plus the form view you provided is working when setting http://xx.xx.xx.xx:xx on every form field. You should trace when the 403 forbidden is triggered. If you make use of XDebug i'd recommend you to trace step by step where the execution fails. Otherwise I'd just start removing code to find out at which point of the execution the exception is occurring. If you are making use of a shared hosting, there could be any rule in the http server that is blocking the request, if that's the case, run it locally using a WAMP/LAMP bundle. // CodeIgniter 4 approach public function add() { if ($this->request->getMethod() == 'post') { $validation = \Config\Services::validation(); $validation->setRule('grup', 'Grup Adı', 'trim|required'); $validation->setRule('name', 'Şube Adı', 'trim|required'); $validation->setRule('ip', 'İp Adresi', 'trim|required'); $validation->setRule('path', 'Database Yolu', 'trim|required'); $validation->setRule('lisans', 'Lisans Tarihi', 'trim|required'); if ($validation->withRequest($this->request)->run() == true) { $data = array( 'name' => $this->request->getPost('name'), 'marka' => $this->request->getPost('grup'), 'ip' => $this->request->getPost('ip'), 'il' => $this->request->getPost('il'), 'ilce' => $this->request->getPost('ilce'), 'databasePath' => $this->request->getPost('path'), 'lisanse_date'=>$this->request->getPost('lisans') ); // $data = $this->security->xss_clean($data); $result = $this->sube_model->add_sube($data); $result = 1; if ($result) { session()->setFlashdata('msg', 'Şube başarılı bir şekilde eklendi!'); return redirect(base_url('admin/subeler')); } } else { $data['view'] = 'admin/subeler/sube_ekle'; return view('layout', $data); } } else { $data['view'] = 'admin/subeler/sube_ekle'; return view('layout', $data); } }
Laravel 8 updating Data using modal
recently m learning how to update data by using modal.i can successfully inserted data by modal but can not update before that when i press on edit button my modal pops up without fetched data. here is my blade file with script- <div> <h5 style="text-align: center">Modal Practice</h5> </div> {{-- ................................... --}} <div class="container"> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop"> Add data </button> {{-- #dd($alldata) --}} <table id="myTable" class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Common Name</th> <th scope="col">Action</th> </tr> </thead> <tbody> #foreach ($alldata as $key => $data) <tr> <th scope="row">{{ $key + 1 }}</th> <td>{{ $data->first_name }}</td> <td>{{ $data->last_name }}</td> <td>{{ $data->common_name }}</td> <td> <a href="#" class="btn btn-warning btn-sm edit" data-bs-toggle="modal" data-bs-target="#editModal">Edit</a> Delete </td> </tr> #endforeach </tbody> </table> </div> <!-- Add Modal --> <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form action="{{ route('savedata') }}" method="POST" class="row g-3"> <div class="modal-body"> #if (session()->has('success')) <div class="alert alert-success"> {{ session()->get('success') }} </div> #endif #csrf <div class="col-md-6"> <label for="inputEmail4" class="form-label">First Name</label> <input type="text" class="form-control" name="first_name"> </div> <div class="col-md-6"> <label for="inputEmail4" class="form-label">Last Name</label> <input type="text" class="form-control" name="last_name"> </div> <div class="col-md-6"> <label for="inputEmail4" class="form-label">Common Name</label> <input type="text" class="form-control" name="common_name"> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Save</button> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Understood</button> </div> </form> </div> </div> </div> {{-- end Add modal --}} <!-- Edit Modal --> <div class="modal fade" id="editModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="staticBackdropLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form action="#" method="POST" id="editForm" class="row g-3"> <div class="modal-body"> #csrf #method('put') <div class="col-md-6"> <label for="inputEmail4" class="form-label">First Name</label> <input type="text" class="form-control" id="fname" name="first_name"> </div> <div class="col-md-6"> <label for="inputEmail4" class="form-label">Last Name</label> <input type="text" class="form-control" id="lname" name="last_name"> </div> <div class="col-md-6"> <label for="inputEmail4" class="form-label">Common Name</label> <input type="text" class="form-control" id="cname" name="common_name"> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Update</button> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </form> </div> </div> </div> {{-- End Edit Modal --}} <!-- JavaScript Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"> </script> <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap5.min.js"></script> <script src="https://cdn.datatables.net/1.10.25/js/dataTables.jqueryui.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var table = $('#myTable').DataTable(); table.on('click', '.edit', function() { $tr = $(this).closest('tr'); if ($($tr).hasClass('child')) { $tr = $tr.prev('.parent'); } var data = table.row($tr).data(); console.log(data); $('#first_name').val(data[1]); $('#last_name').val(data[2]); $('#common_name').val(data[3]); $('#editForm').attr('action', '/savedata' + data[0]); $('#editModal').modal('show'); }); }); </script> here is controller- public function update(Request $request,$id) { $alldata = DataSave::find($id); $alldata->update([ 'first_name'=>$request->first_name, 'last_name'=>$request->last_name, 'common_name'=>$request->common_name ]); return redirect()->route('index')->with('success', 'Update Successful');; } } and here is my route- Route::get('/index',[SaveController::class,'index'])->name('index'); Route::post('/save',[SaveController::class,'savedata'])->name('savedata');
to get a modal pop-up with fetched data i use something like (look id=""): <!-- Add Modal --> <div class="modal fade" id="editModal{{ $id }}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> </div> And button link to modal should be like (look data-target=""): <td> <a href="#" class="btn btn-warning btn-sm edit" data-toggle="modal" data-target="#editModal{{ $id }}">Edit</a> Delete </td>
Laravel REST API generating 500 internal server error during inserting data from controller to model
I have created a REST API for inserting data from Modal. After submitting my form I get data from my "store" controller. But when I call a Model function to insert that data to Database then I am getting 500 internal server error at console. I have tried with two ways 1. Using Eloquent ORM 2. Using Query Builder My controller: public function store(Request $request) { $category_name = $request->category_name; $category_entry_date = $request->category_entry_date; $category_info = array( 'Supplier_Name' => $category_name, 'Supplier_Des' => $category_entry_date, 'Shop_Id' => 1 ); // Insert data into database Product::CreateProductCategory($category_info); return response()->json(['success_massege'=>'Category Added Successfully']); } Js: $("#category_submit").click(function (e) { event.preventDefault(); var category_name = $('#category_name_id').val(); var category_entry_date = $('#category_entry_date_id').val(); if (category_name && category_entry_date) { $.post("/api/api/product_category", {category_name: category_name, category_entry_date: category_entry_date}).done(function (data) { $('#category_name_id').val(""); $('#category_entry_date_id').val(""); var success_massege_dialogbox = ''; success_massege_dialogbox += '<div class="alert alert-success fade in">'; success_massege_dialogbox += '×'; success_massege_dialogbox += '<strong>Success!</strong>' + data.success_massege + '</div>'; $('#success_massege').append(success_massege_dialogbox); }); } else { alert('Please give a category name and entry date'); } }); Model: static function CreateProductCategory($category_info){ DB::table('product_category_info')->insert($category_info); } View: <div class="modal fade" id="addCategory" tabindex="-1" role="dialog" aria-labelledby="addCategoryLabel"> <div class="modal-dialog" role="document"> <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="addCategoryLabel">Add Category</h4> </div> <form action="{{ route('product_category.store') }}" method="POST"> <div class="modal-body"> <div class="modal-body"> <div class="box-body"> <div class="row form-group"> <div class="col-md-3 form-level"></div> <div class="col-md-9" id="success_massege"> </div> </div> <div class="row form-group"> <div class="col-md-3 form-level"><label>Category Name<b class="mandetory_star">*</b></label></div> <div class="col-md-9" id="email-error-dialog"> {{Form::text('category_name','', $attributes = array('class' => 'form-control', 'id' => 'category_name_id', 'data-validation'=>'alphanumeric', 'data-validation-allowing'=>'-_', 'data-validation-error-msg'=>'Please Enter a Valid Category Name', 'data-validation-error-msg-container'=>'#email-error-dialog', ))}} </div> </div> <div class="row form-group"> <div class="col-md-3 form-level"><label>Entry Date<b class="mandetory_star">*</b></label></div> <div class="col-md-9" id="date-error-dialog"> {{Form::date('entry_date','', $attributes = array('class' => 'form-control', 'id' => 'category_entry_date_id', 'data-validation'=>'date', 'data-validation-error-msg'=>'Please Enter a Valid Date', 'data-validation-error-msg-container'=>'#date-error-dialog'))}} </div> </div> </div><!-- /.box-body --> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button id="category_submit" type="submit" class="btn btn-primary save-category"> Save category </button> </div> </form> </div> </div> </div>
There are lots of records coming in my foreach loop, I want to display only two records
#foreach (var item in Model) { <div class="row leftimages"> <div class="col-md-6 col-xs-12 col-sm-12 innerimage"> <img src="#Html.DisplayFor(modelItem => item.ImageUrl)" class="img-responsive1"> </div> <div class="col-md-6 col-xs-12 col-sm-12"> <h4 class="tag">#Html.DisplayFor(modelItem => item.Title)</h4> <h5 class="greentext">#Html.DisplayFor(modelItem => item.VendorName)</h5> <h5 class="freeship"></h5> #{ if (item.OfferPrice.HasValue) { <h5 class="freeship">Discount Available of #Html.DisplayFor(modelItem => item.Discount)%</h5> <h4 class="price"> #Html.DisplayFor(modelItem => item.OfferPrice) <span class="oldprice" style="text-decoration: line-through;"> #Html.DisplayFor(modelItem => item.OriginalPrice)</span></h4> } } </div> <div class="col-md-12"> <p class="paragraph"> #Html.DisplayFor(modelItem => item.ProductDescription)</p> </div> </div> <div class="row blackstrip"> <div class="col-md-2 col-xs-3"> <h5 class="lefticons"><img src="images/like.png" >Like</h5> </div> <div class="col-md-2 col-xs-3 icon"> <h5 class="lefticons"><img src="images/share.png">Share</h5> </div> <div class="col-md-2 col-xs-3 icon"> <h5 class="lefticons"><img src="images/more.png">More</h5> </div> <div class="col-md-3 col-xs-3 col-md-offset-3 buy"> <h4 class="buynow">Buy Now</h4> </div> </div> }
You can use full power of LINQ #foreach (var item in Model.Take(2)) better yet, you would want to limit amount of data returned from database in your controller. like db.YourDbSet.Where(x=> some condition).Take(2).ToList()
why partial view not loading
I have jquery like this and i am trying to load partial view but it not working it shows dialog box without any control mvcJqGrid.demo.edit = function(id) { var grid = $('#Products'); var myCellData = grid.jqGrid('getCell', id, 'ProductId'); GetProduct(myCellData); return false; }; function GetProduct(id) { $("#dialog-form").load("#Url.Action("EditProduct","Admin")", function (response, status, xhr) { $("#dialog-form").dialog('open'); }); } ; my action is: [HttpPost] public ActionResult EditProduct(string productId) { int id = 0; Product product = null; bool result = int.TryParse(productId,out id); ProductModel productModel=new ProductModel(); Session["ProductModule"] = productModel.GetProduct(id); return PartialView("Product_Partial", Session["ProductModule"] as ProductModel); //return RedirectToAction("Product", "Admin"); } my Partial View is: #using (Html.BeginForm("Product","Admin",method:FormMethod.Post)) { <fieldset> <legend>Product Information</legend> <div class="editor-label"> #Html.LabelFor(m => m.ProductTitle) </div> <div class="editor-field"> #Html.TextBoxFor(m => m.ProductTitle) </div> <div class="editor-label"> #Html.LabelFor(m => m.ProductTypeId) </div> <div> <select name="ProductType"> <option value="null">Select ProductType</option> #foreach (var row in new Database("MyConnectionString").Query<LookUp>("select * from Lookup where LookupTypeId=(select LookupTypeId from LookupType where LookupTypeName=#0)", "ProductType")) { <option value="#row.LookupId">#row.LookupName</option> } </select> </div> <div class="editor-label"> #Html.LabelFor(m => m.BrandId) </div> <div > <select name="Brand"> <option value="null">Select Brand</option> #foreach (var row in new Database("MyConnectionString").Query<LookUp>("select * from Lookup where LookupTypeId=(select LookupTypeId from LookupType where LookupTypeName=#0)", "Brand")) { <option value="#row.LookupId">#row.LookupName</option> } </select> </div> <div class="editor-label"> #Html.LabelFor(m => m.BasePrice) </div> <div class="editor-field"> #Html.TextBoxFor(m => m.BasePrice) </div> <div class="editor-label"> #Html.LabelFor(m => m.ProductSpecification) </div> <div class="editor-field"> #Html.TextBoxFor(m => m.ProductSpecification) </div> <div class="editor-label"> #Html.LabelFor(m => m.ProductSummary) </div> <div class="editor-field"> #Html.TextBoxFor(m => m.ProductSummary) </div> <div class="editor-label"> #Html.LabelFor(m => m.IsOutOfStock) </div> <div class="ui-icon-check"> #Html.CheckBoxFor(m => m.IsOutOfStock) </div> <table> <tr> <td> <input type="submit" value="Add" onclick="#Url.Action("Product", "Admin")" /> </td> <td> <button type="submit" id="btnDelete" name="Command" value="Update" onclick="#Url.Action("Product", "Admin")" >Update</button> </td> <td> <button type="submit" id="btnSearch" name="Command" value="Delete" onclick="#Url.Action("Product", "Admin")">Delete</button> </td> </tr> </table> </fieldset> } my view page : <div id="dialog-form" title="Add New Product"> </div>
I don' t see the initialization of the plugin here.. i see directly : $("#dialog-form").dialog('open'); but where initialize you the dialog with options ? i think that you should initialize dialog in your success response instead of calling directly the function 'open'. Look at doc jquery ui dialog $("#dialog-form").load("#Url.Action("EditProduct","Admin")", function (response, status, xhr) { $( "#dialog-form" ).dialog(); }); I hope that'll help you