Laravel 5.2 TokenMismatchException - laravel

I'd like to write a code in Laravel 5.2 which would upload photos, my problem is that once I start uploading many photos at once the site goes down.
It gives me this error: TokenMismatchException in VerifyCsrfToken.php line 67:
This error should appear only when the {{ csrf_field() }}, is missing from the form, but in this case it isn't, it's right there.
It works perfectly with less images. What could be the problem?
Controller
public function store(Request $request)
{
$rules = array(
'picturess' => 'mimes:jpeg,jpg,bmp,png',
);
$messages = array(
'mimes' => 'A feltöltetni kívánt kép nem felel meg a kritériumoknak. (Ilyen lehet a kép kiterjesztése: jpeg, jpg, bmp vagy png. A kép se lehet bármekkora.)',
'integer' => 'A beírt szőveg nem szám.',
'required' => 'Ennek a mezőnek a kitőltése kötelező.',
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withInput()->withErrors($validator);
}
if (Input::hasFile('pictures')) {
$files = $request::file('pictures');
$file_count = count($files);
$uploadcount = 0;
$destinationPath = 'uploads';
$userId = Auth::user()->id;
foreach ($files as $file) {
if ($file->isValid()) {
$extension = $file->getClientOriginalExtension();
$pictureFileName = $this->makePictureFileName(0, $extension);
$thumbnailPictureFileName = $this->makePictureFileName(1, $extension);
Log::info('pictureFileName: '.$pictureFileName);
if ($file->move($destinationPath, $pictureFileName)) {
$uploadcount++;
$img = Image::make($destinationPath . '/' . $pictureFileName);
//$img = Image::make($file->getClientOriginalName());
$img->resize(277, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save($destinationPath . '/' . $thumbnailPictureFileName);
$picture = new Picture;
$picture->filename = $pictureFileName;
$picture->thumbnail_filename = $thumbnailPictureFileName;
$picture->user_id = $userId;
$picture->save();
}
} else {
Session::flash('picture-error', 'A feltöltetni kívánt kép nem megfelelő. (Valószínűleg túl nagy.)');
return redirect()->back()->withInput()->withErrors($validator);
}
}
if ($uploadcount == $file_count) {
Session::flash('success', 'A képek feltöltése sikeres.');
} else {
return redirect()->back()->withInput()->withErrors($validator);
}
}
//return Redirect::to('pictures/create');
return redirect()->back()->withInput()->withErrors($validator);
}
View
#extends('layouts.site')
#section('content')
<div class="row">
<div class="col-md-12">
{!! Form::open(array('method' =>'POST', 'url' => 'pictures', 'class' => 'uk-form', 'files'=> true)) !!}
{{ csrf_field() }}
<div class="form-group">
{!! Form::label('pictures', 'Kép', array('class' => '')) !!}
<div class="uk-form-controls">
{!! Form::file('pictures[]', array('class' => '','multiple'=>true)) !!}
</div>
</div>
<div class="form-group">
<button class="uk-button">Küldés</button>
</div>
#if ($errors->has('success'))
<div class="alert alert-danger" role="alert">
<p>{{ $errors->first('success') }}</p>
</div>
#endif
#if(Session::has('picture-error'))
<div class="alert alert-danger" role="alert">
<p class="errors">{!! Session::get('error') !!}</p>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::close() !!}
</div>
</div>
#stop
Route
Route::group(['middleware' => ['web']], function () {
Route::get('/', 'SiteController#index');
Route::get('admin', 'AdminController#index');
Route::resource('pictures', 'PicturesController');
Route::resource('users', 'UsersController');
Route::auth();
});

{!! Form::open... will automatically add CSRF field protection, so you don't need this {{ csrf_field() }}.

Related

Laravel filter reset after next page click in paginate

I have created a table were showing data. I also add few filters to filter data. Using paginate I show 20 records per page. After select filter and click search records in table filter with paginating on the first page but as soon as I click next page filters getting reset. How to stop filters from getting reset?
Below is my code,
public function index()
{
$agos = DB::table('orders')
->leftJoin('companies', 'orders.company_id', '=', 'companies.id')
->select(DB::raw('orders.id, companies.name, orders.type, orders.data, orders.currency, orders.price, orders.status, DATE_FORMAT(orders.created_at,"%M %d, %Y") as created_at '))
->where('orders.merchant', '=', 'agos')
->where(function ($query) {
$status = Input::has('status') ? Input::get('status') : null;
$company = Input::has('company') ? Input::get('company') : null;
$from = Input::has('from_date') ? Input::get('from_date') : null;
$to = Input::has('to_date') ? Input::get('to_date') : null;
$from = date("Y-m-d", strtotime($from));
$to = date("Y-m-d", strtotime($to));
if ( isset($status) ) {
$query->where('orders.status', '=', $status);
}
if ( isset($company) ) {
$query->where('companies.name', '=', $company);
}
if ( !empty($from) && !empty($to) ) {
$query->whereBetween('orders.created_at', [$from, $to]);
}
})->orderBy('orders.created_at', 'desc')
->paginate(20);
return $agos;
}
Blade file code,
#extends('layouts.agos')
#section('title', Translator::transSmart('app.Common Clerk(AGOS)', 'Common Clerk(AGOS)'))
#section('styles')
#parent
{{ Html::skinForVendor('jquery-textext/all.css') }}
#endsection
#section('scripts')
#parent
{{ Html::skinForVendor('jquery-textext/all.js') }}
#endsection
#section('content')
<div class="admin-managing-member-index">
<div class="row">
<div class="col-sm-12">
{{ Form::open(array('route' => array('agos::index'), 'class' => 'form-search')) }}
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'company';
$translate = Translator::transSmart('app.Company', 'Company');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{ Form::select($name, $companies->pluck('name', 'name'), Request::get($name), array('id' => $name, 'title' => $translate, 'class' => 'form-control', 'title' => $name, 'placeholder' => '')) }}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'status';
$translate = Translator::transSmart('app.Status', 'Status');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
{{Form::select($name, Utility::constant('agos_status', true), Request::get($name), array('id' => $name, 'class' => 'form-control', 'title' => $translate, 'placeholder' => ''))}}
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'from_date';
$translate = Translator::transSmart('app.From', 'From');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#php
$name = 'to_date';
$translate = Translator::transSmart('app.To', 'To');
#endphp
<label for="{{$name}}" class="control-label">{{$translate}}</label>
<div class="input-group schedule">
{{Form::text($name, '' , array('id' => $name, 'class' => 'form-control datepicker', 'readonly' => 'readonly', 'title' => $translate, 'placeholder' => ''))}}
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12 toolbar">
<div class="btn-toolbar pull-right">
<div class="btn-group">
{{
Html::linkRouteWithIcon(
null,
Translator::transSmart('app.Search', 'Search'),
'fa-search',
array(),
[
'title' => Translator::transSmart('app.Search', 'Search'),
'class' => 'btn btn-theme search-btn',
'onclick' => "$(this).closest('form').submit();"
]
)
}}
</div>
</div>
</div>
</div>
{{ Form::close() }}
</div>
</div>
<div class="row" >
<div class="col-sm-12">
<hr />
</div>
</div><br>
<div class="row" style="background-color:#FFFFFF">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-condensed table-crowded">
<thead>
<tr>
<th>{{Translator::transSmart('app.#', '#')}}</th>
<th></th>
<th>{{Translator::transSmart('app.Company', 'Company')}}</th>
<th>{{Translator::transSmart('app.Products', 'Products')}}</th>
<th>{{Translator::transSmart('app.Total Price', 'Total Price')}}</th>
<th>{{Translator::transSmart('app.Status', 'Status')}}</th>
<th>{{Translator::transSmart('app.Created At', 'Created At')}}</th>
<th></th>
</tr>
</thead>
<tbody>
#if($orders->isEmpty())
<tr>
<td class="text-center empty" colspan="14">
--- {{ Translator::transSmart('app.No Record.', 'No Record.') }} ---
</td>
</tr>
#endif
<?php $count = 0;?>
#foreach($orders as $order)
<tr>
<td>{{++$count}}</td>
<td></td>
<td>{{$order->name}}</td>
<td>
#php
$json = $order->data;
$json = json_decode($json, true);
$products = $json['order_info']['products'];
$data = '';
foreach ($products as $hitsIndex => $hitsValue) {
$data .= $hitsValue['name']. ', ';
}
$data = rtrim($data, ', ');
#endphp
{{$data}}
</td>
<td>
#if(empty($order->price) || $order->price == 0)
{{'Quotation'}}
#else
{{CLDR::showPrice($order->price, $order->currency, Config::get('money.precision'))}}
#endif
</td>
<td>{{Utility::constant(sprintf('agos_status.%s.name', $order->status))}}</td>
<td>{{$order->created_at}}</td>
<td class="item-toolbox">
{{
Html::linkRouteWithIcon(
'agos::edit',
Translator::transSmart('app.Edit', 'Edit'),
'fa-pencil',
['id' => $order->id],
[
'title' => Translator::transSmart('app.Edit', 'Edit'),
'class' => 'btn btn-theme'
]
)
}}
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="pagination-container">
#php
$query_search_param = Utility::parseQueryParams();
#endphp
{!! $orders->render() !!}
</div>
</div>
</div>
</div>
#endsection
Controller Code,
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Can someone help me?
Try to append the request in the results:
public function index(Request $request){
try {
$companies = (new Company())->showAllCompanyWithName(['name' => 'ASC'], false);
$orders = (new Agos())->index();
$queryArgs = Input::only(['status','company','from_date', 'to_date']);
$orders->appends($queryArgs);
} catch (InvalidArgumentException $e) {
return Utility::httpExceptionHandler(500, $e);
} catch (Exception $e) {
return Utility::httpExceptionHandler(500, $e);
}
$view = SmartView::render(null, compact($this->singular(), $this->plural(), 'companies', 'orders'));
return $view;
}
Then in your template:
<div class="pagination-container">
{!! $orders->render(); !!}
</div>
try to use in your Blade view
$orders->links()

Update 2 tables with 1 form in laravel

I have users table and profiles table, now i want let users to update their info in single form.
Logic
name & email will update in users table
rest of the fields will update in profiles table
Code
blade (form)
{{ Form::model($user, array('route' => array('profileupdate', $user->id), 'method' => 'PUT','files' => true)) }}
<div class="row">
<div class="col-md-6">
<label for="name">Name</label>
{{Form::text('name', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="email">Email</label>
{{Form::text('email', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="about">About</label>
{{Form::textarea('about', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<div class="row">
<div class="col-md-6">
<label for="phone">Phone</label>
{{Form::text('phone', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6">
<label for="website">Website</label>
{{Form::text('website', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="state">State</label>
{{Form::text('state', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-6 mt-3">
<label for="city">City</label>
{{Form::text('city', null, array('class' => 'search-field'))}}
</div>
<div class="col-md-12 mt-3">
<label for="photo">Photo</label>
{{Form::file('photo', array('class' => 'search-field'))}}
</div>
</div>
</div>
<div class="col-md-12">
{{ Form::submit('Update', array('class' => 'btn btn-success mt-5')) }}
</div>
</div>
{{Form::close()}}
Screenshot (code above)
controller
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
$user->save();
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
PS: please don't go with my controller method, I just put data that
way so you can know what field belongs to what table.
Question
Any idea how i can save my data in 2 tables at the same time?
And I get this Error
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException No message
You need to check whether save in both or not
public function update(Request $request, $id)
{
$user = User::find($id);
$user = User::where('id',$id)->first();
$user->name = $request->input('name');
if($user->save())
{
$profile = Profile::find($id);
$profile = Profile::where('id',$id)->first();
$profile->user_id = $request->input('user_id');
$profile->about = $request->input('about');
$profile->website = $request->input('website');
$profile->phone = $request->input('phone');
$profile->state = $request->input('state');
$profile->city = $request->input('city');
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$filename = 'photo' . '-' . time() . '.' . $photo->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($photo)->resize(1300, 362)->save($location);
$profile->photo = $filename;
$oldFilename = $profile->photo;
$profile->photo = $filename;
Storage::delete($oldFilename);
}
$profile->save();
return redirect()->route('profile', $user->id)->with('success', 'Your info are updated');
}
return redirect()->back()->with('error','Something went wrong');
}
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException this exception comes when you are trying to access post method by hiiting the url in browser.
Since you can't insert into multiple tables in one MySQL command, there is no way to accomplish your requirement. But You can however use a Single Transaction.
DB::transaction(function() {
// first update
User::whereId($id)->update([
'name' => $reqquest->name,
'email' => $request->email,
..........
]);
// second update
Profile::whereId($id)->update([
'about' => $request->website,
'mobile' => $request->mobile,
..........
..........
]);
}

laravel 5.2 Restfull Api with admin panel stop working suddenly

I developed admin panel to add,edit,delete users in my website with Restfull Api. edit and delete work fine but add not.
when I add user it may work or this error may appear
The localhost page isn’t working
localhost is currently unable to handle this request.
This is my routes
Route::resource('admin/users','AdminUser');
This is store function in Admin user resource
public function store(Request $request)
{
//rules
$rules = array(
'name' => 'required',
'email' => 'required|email',
'password' => 'required|min:6|confirmed',
'password_confirmation' => 'required|min:6'
);
/*
validate the data user
**/
$validator = Validator::make($request->all(),$rules);
if ($validator->fails()) {
return view('admin.User.create_user')
->withErrors($validator)
->withInput(['page' => 'home']);
}
/*
Store the data user in the database
**/
$user = new User;
$user->name =$request->input('name');
$user->email = $request->input('email');
$user->password=bcrypt($request->input('password'));
$user->role='user';
$user->save(); //error here
//redirect
return redirect('admin/users')->with('message', 'Successfully added user!');
}
And this is create_user.blade.php
#extends('layouts.layout')
#section('content')
<section id="advertisement">
<div class="container">
<img src="{{asset('images/shop/advertisement.jpg')}}" alt="" />
</div>
</section>
<section>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="left-sidebar">
#include('shared.sidebaradmin')
</div>
</div>
<div class="features_items"><!--features_items-->
<h2 class="title text-center">Add New Product</h2>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{{ Form::open(array('url' => 'admin/users')) }}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name',null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'Email') }}
{{ Form::email('email',null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('password_confirmation', 'Confirm Password') }}
{{ Form::password('password_confirmation', array('class' => 'form-control')) }}
</div>
{{ Form::submit('Add a new user !', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div><!--features_items-->
</div>
</div>
</section>
#endsection

Session::flash('success', 'Data has been saved successfully');

I am using the following code to show flash message, but it is not working.
PostController
public function store(Request $request){
$this->validate($request,array(
'title'=>'required|max:255',
'slug' =>'required|alpha_dash|min:5|max:255|unique:posts,slug',
'body' =>'required'
));
//store in the database
$post = new Post;
$post->title = $request->title;
$post->slug = $request->slug;
$post->body = $request->body;
$post->save();
//This code will generate flash message about success or failure about data insert
Session::flash('success', 'Data has been saved successfully!');
//Redirect to another page
return redirect()->route('posts.show', $post->id);
}
Then to display it the following code is used:
message.blade.php
#if(Session::has('success'))
<div class="alert alert-success" role= "alert">
<strong>Successful:</strong>
{{ Session::get('success') }}
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger" role="alert">
<strong>Errors:</strong>
<ul>
#foreach($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
The code above is not showing any flash message. But when
Session::flash('success', 'Data has been saved successfully!');
is written as:
Session::put('success', 'Data has been saved successfully!');
the flash message is displayed and does not disappear.
The routes.php is :
Route::group(['middleware' => ['web']], function(){
Route::get('auth/login', ['as' =>'login', 'uses'=>
'Auth\AuthController#getLogin']);
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', ['as' => 'logout', 'uses' =>
'Auth\AuthController#getLogout']);
Route::get('auth/register','Auth\AuthController#getRegister');
Route::post('auth/register','Auth\AuthController#postRegister');
Route::get('password/reset/{token?}',
'Auth\PasswordController#showResetForm');
Route::post('password/email',
'Auth\PasswordController#sendResetLinkEmail');
Route::post('password/reset','Auth\PasswordController#reset');
Route::get('contact', 'PagesController#getContact');
Route::get('about', 'PagesController#getAbout');
Route::get('/', 'PagesController#getIndex');
Route::get('reader/{slug}', ['as' => 'reader.single', 'uses' =>
'ReaderController#getSingle'])
->where('slug', '[\w\d\-\_]+');
Route::get('reader', ['as' => 'reader.index', 'uses' =>
'ReaderController#getIndex' ]);
Route::resource('posts', 'PostController');
});
Help please!
1.- Make sure if u are including the message template on your view, in this case your SHOW view
2.- Try replacing your message template for this:
#if(Session::has('success'))
<div class="alert alert-success" role= "alert">
<strong>Successful:</strong>
{!! session('success') !!}
</div>
#endif
#if(count($errors) > 0)
<div class="alert alert-danger" role="alert">
<strong>Errors:</strong>
<ul>
#foreach($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
Look, i'm using {!! session('success') !!} instead of yours

MethodNotAllowedHttpException Laravel

I'm having trouble with an error that I'm getting in laravel. When I run my code on localhost I don't have any issues, but when I placed laravel in demo live server which is server ('https') I get the MethodNotAllowedHttpException error.
Here's my code for my route
Route::post('post_reminder', function(){
$creds = array(
'email' => Input::get('email')
);
$rules = array(
'email' => 'required|email'
);
$messages = array(
'email' => 'The :attribute needs to be an real email'
);
$validator = Validator::make($creds, $rules,$messages);
if($validator->fails())
{
return Redirect::route('getReminder')->withErrors($validator);
}
else
{
return Password::remind($creds);
}
});
And here's the form code
<div id="reset_container">
{{ Form::open(array('url' => 'post_reminder')) }}
<h1 id="pass_recovery_text">Password Recovery Form</h1>
<p>
#if (Session::has('error'))
<li id="error">{{ trans(Session::get('reason')) }}</li>
#elseif (Session::has('success'))
<li id="error">An e-mail with the password reset has beensent.</li>
#endif
#foreach($errors->all() as $error)
<li id="error">{{ $error }}</li>
#endforeach
{{ Form::label('email', 'Please enter you email: ') }}
{{ Form::text('email','',array('id' => 'forgot')) }}
{{ Form::submit('Reset') }}<br /><br /><br />
{{ HTML::link('/', 'Have a account Sign-In', array('id' => 'sign-in')) }}
</p>
{{ Form::close() }}
</div>
<div id="reset_container">
{{ Form::open(array('url' => 'post_reminder','method' => 'post')) }}
<h1 id="pass_recovery_text">Password Recovery Form</h1>
<p>
#if (Session::has('error'))
<li id="error">{{ trans(Session::get('reason')) }}</li>
#elseif (Session::has('success'))
<li id="error">An e-mail with the password reset has beensent.</li>
#endif
#foreach($errors->all() as $error)
<li id="error">{{ $error }}</li> #endforeach
{{ Form::label('email', 'Please enter you email: ') }}
{{ Form::text('email','',array('id' => 'forgot')) }}
{{ Form::submit('Reset') }}
{{ HTML::link('/', 'Have a account Sign-In', array('id' => 'sign-in')) }} </p>
{{ Form::close() }}
Have you tried force the route to be served over https?
Route::post('post_reminder', array('https', function(){
$creds = array(
'email' => Input::get('email')
);
$rules = array(
'email' => 'required|email'
);
$messages = array(
'email' => 'The :attribute needs to be an real email'
);
$validator = Validator::make($creds, $rules,$messages);
if($validator->fails())
{
return Redirect::route('getReminder')->withErrors($validator);
}
else
{
return Password::remind($creds);
}
}));
Referencing to http://laravel.com/docs/4.2/routing here.

Resources