Laravel 5: How to use button? - laravel-5

I'm a newbie in laravel 5.. and i don't know how to use button function.. I need to save the data in database but i don't know how to do it.. Thanks for the help!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Create</title>
<link rel="stylesheet" href="">
</head>
<body>
<div><input type="text" placeholder="Enter Name here" name="name"></div>
<div><input type="text" placeholder="Author" name="author"></div>
<div><input type="hidden" name="action_create"></div>
<div><textarea name="content" id="" cols="30" rows="10"></textarea</div>
<div><button type="button">Button</button></div>
</body>
</html>
this is my route
$router->get('create',['uses' => "TestController#create"]);
$router->post('create',['uses' => "TestController#store"]);
$router->get('edit/{blog_id?}',['uses' => "TestController#edit"]);
$router->post('edit/{blog_id?}',['uses' => "TestController#update"]);
$router->get('view',['uses' => "TestController#view"]);
$router->get('/',['uses' => "TestController#index"]);
public function store(InputRequest $input){
// return 'lkjlasd';
$new_blog = new Blog;
$new_blog->fill($input->all());
if($new_blog->save()){
echo "save success.";
}else{
echo "db communication error";
}
}

to start without creating a form will be unable to send anything on your form
The way is your not send anything
Index
<form method="POST" action="backend" accept-charset="UTF-8" name="InsertData" role="form">
<div><input type="text" placeholder="Enter Name here" name="name"></div>
<div><input type="text" placeholder="Author" name="author"></div>
<div><input type="submit" value="Insert"></div>
</form>
In your route:
Here you will call your action of your form eg "backend"
Route::get('backend','Controller#InsertData');
In your controller
The controller uses the eloquent in order to save the content in your database
public function updateSocial() {
$new_blog = Input::except('_token');
$validation = Validator::make($new_blog, Blog::$new_blog);
if ($validation->passes()) {
$new_blog = new Blog;
$new_blog->name = Input::get('name');
$new_blog->author= Input::get('author');
$new_blog->save();
Session::flash('insert', 'success');
return Redirect::to('backend');
} else {
return Redirect::to('backend')->withInput()->withErrors($validation);
}
}
In your model
Will draw variable and here is their validations
public static $new_blog = array(
'name' => 'required',
'author' => 'required',
);
I hope help you

Extending the anwser on #Jose Cerejo's answer:
Add {{ csrf_field() }} to the form.
What you doing with your routes is exacly the same as:
$router->resource('/', TestController::class);
Checkout the documentation here.
EDIT:
You could use Laravel Collective to do something like this:
{!! Form::open(['action' => 'TestController#store']) !!}
<div>
{!! Form::text('name', null, [ 'placeholder' => 'Enter Name here' ]) !!}
</div>
<div>
{!! Form::text('author', null, [ 'placeholder' => 'Author' ]) !!}
</div>
<div>
{!! Form::submit('Insert') !!}
</div>
{!! Form::close() !!}
It creates the form with the necessary hidden fields for you (like crsf token and a _method field for the update PUT requests)

Related

Trying to get property 'username' of non-object after POST to external website and redirect back to my website in LARAVEL

Auth::user() has a POST request to an external website with the following:
postfile.blade.php
<form action="{{ url('https:www.external.com/api/') }}" method="POST" align="center">
#csrf
#method('POST')
<input type="hidden" name="Data1" value="{{ $Data1}}">
<input type="hidden" name="Data2" value="{{ $Data2}}">
<input type="hidden" name="Data3" value="{{ $Data3}}">
<input type="hidden" name="ReturnURLOK" value="{{ url('/success') }}">
<input type="hidden" name="ReturnURLError" value="{{ url('/fail') }}">
<button type="submit" value="POST TO API">PROCEED/button>
</form>
After which, https:www.external.com/api/ provides a POST request back to Auth::user() url wherein the data are saved on database.
Controller:
public function postfiles(Request $request)
{
$request->session()->put('user_id',Auth::user()->id);
return view('postfile');
}
public function parse(Request $request)
{
$files = File::create([
'Data4' => $request->input('Data4'),
'Data5' => $request->input('Data5'),
'Data6' => $request->input('Data6'),
]);
$data = array(
'Data4' => $request->input('Data4'),
'Data5' => $request->input('Data5'),
'Data6' => $request->input('Data6'),
);
Auth::loginUsingId($request->session()->get('user_id'));
return view('success')->with($data);
}
The data are being saved correctly but in the success.blade.php I'm getting an error when I try to display the data on the blade.
Error is
Trying to get property 'username' of non-object
success.blade.php
<div class="container">
<div>
<h3>CONGRATULATIONS {{ Auth::user()->username}}!</h3>
<h2>The following Data has been saved</h2>
{{ $Data4}}
{{ $Data5}}
{{ $Data6}}
</div>
</div>
Routes:
Route::group(['middleware' => ['auth', 'activated', 'currentUser']], function () {
Route::get('postfile', 'App\Http\Controllers\FileController#postfiles')->name('postfile');
Route::POST('success', 'App\Http\Controllers\FileController#parse')->name('parse');
});
It seems the user's session is somehow lost and Auth::user() becomes null after being redirected back during the POST request from the external website.
i dont know why your logged-in user is lost but:
one solution i can say is that you can save id of that user somewhere like coockie or session and after redirecting back from your api, you get that id and re-login that user

laravel livewire return blank page after submit form

Im learning laravel livewire but i encounter this problem, i followed the tutorial in youtube but i dont know what is the problem.
login.blade.php
I have this in form tag wire:submit.prevent="submit"
app.blade.php
#livewireStyles
<livewire:login />
#livewireScripts
Login Component
public $form = [
'username' => '',
'password' => '',
];
public function submit()
{
$this->validate([
'form.username' => 'required',
'form.password' => 'required'
]);
}
public function render()
{
return view('livewire.login');
}
I have same error.
My code is:
#if($errors->any())
<ul>
[laravel error loop]
</ul>
#endif
<div class="anything">
<form wire:submit.prevent="save">
....form tags....
</form>
</div>
It seems livewire not rendering any other html after perfectly closed, like above, after </ul> is closed, then the rest is no rendering
Then I change my code to:
<div class="anything">
#if($errors->any())
<ul>
[laravel error loop]
</ul>
#endif
<form wire:submit.prevent="save">
....form tags....
</form>
</div>
I wrap all elements in one <div>, in this case I use <div class="anything"> And it works!
My form rendered!

I Cannot able to pass the id in route file in laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:
If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id
Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.
Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

How to use cashier package in laravel 5.2?

I am creating a user subscription plan, For this I am using cashier package in laravel 5.2. I am following the exact way in provided in the tutorial given in laravel document https://laravel.com/docs/5.2/billing. But I am getting the error
ErrorException in FacebookScraperController.php line 1767:
Undefined variable: creditCardToken
my controller code:
$user = User::find(2);
$res = $user->newSubscription('main', 'monthly')->create($creditCardToken);
dd($res);
What should I pass the value inside the $creditCardToken variable.
I tried to give the card details inside this variable. But getting error.
Please help me out.
You will need to pass the subscription plan here with the token generated at the time of card entry.
Here is the step you can follow.
create a view page:
<form action="/subscription" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script type="text/javascript">
Stripe.setPublishableKey('pk_test_TSGgkchoa9iQU4ZQ628a8Auz');
</script>
<script>
$(function() {
var $form = $('#payment-form');
$form.submit(function(event) {
// Disable the submit button to prevent repeated clicks:
$form.find('.submit').prop('disabled', true);
// Request a token from Stripe:
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from being submitted:
return false;
});
});
function stripeResponseHandler(status, response) {
// Grab the form:
var $form = $('#payment-form');
if (response.error) { // Problem!
// Show the errors on the form:
$form.find('.payment-errors').text(response.error.message);
$form.find('.submit').prop('disabled', false); // Re-enable submission
} else { // Token was created!
// Get the token ID:
var token = response.id;
// Insert the token ID into the form so it gets submitted to the server:
$form.append($('<input type="hidden" name="stripeToken">').val(token));
// Submit the form:
$form.get(0).submit();
}
};
</script>
and in your controller:
public function subscription(Request $request)
{
$user = User::find(1);
$creditCardToken = $request->stripeToken;
$res = $user->newSubscription('main', 'pro')
->trialDays(30)
->create($creditCardToken, [
'plan' => 'pro',
'email' => $user->email,
]);
}

How to fix NotFoundHttpException laravel?

Hi all I am a new of laravel 5.1,I just start learning laravel. I have problame in laravel I can not find the way to correct it I try to search but I still can not.I want to update form, but when I click button update its show error
NotFoundHttpException in Handler.php line 46: No query results for model [App\Course].
ModelNotFoundException in Builder.php line 129: No query results for model [App\Course].
And here is my code:
CourseController.php
public function update(Request $request, $id)
{
$input = $request->all();
$data = Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
and my model Course.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $table = "course";
protected $primaryKey = "course_id";
protected $fillable=[
'course_title',
'course_code',
'course_credite'
];
}
And here is my view edite.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<div class="container">
{!! Form::open(array('route'=>['course.update','$course->course_id'],'class'=>'jack','method'=>'PUT')) !!}
{!! Form::label('Course_title','Course Title',array('class'=>'aswe')) !!}
{!! Form::text('course_title', $value=$course->course_title, $att = array('class'=>'blu','id'=>'single','required')) !!}
{!! Form::label('Course_code','Code_title',array('class'=>'no')) !!}
{!! Form::text('course_code',$value=$course->course_code,$att = array('class','blue','required')) !!}
{!! Form::label('Course_creadit','creadit_title',array('class'=>'no')) !!}
{!! Form::text('course_credite',$value=$course->course_credite,$att = array('class','blue','required')) !!}
{!! Form::submit('submit',$att=array('class'=>'has')) !!}
{!! Form::close() !!}
</div>
</body>
</html>
And my route
Route::resource('course','CourseController');
It looks like the problem is how you're opening the form:
{!! Form::open(array('route'=>['course.update','$course->course_id'],'class'=>'jack','method'=>'PUT')) !!}
There are single-quotes around the parameter to the route, so it'd be looking to pass in the literal string "$course->course_id". To fix this, you can simply remove those quotes:
{!! Form::open(['route' => ['course.update', $course->course_id], 'class' => 'jack', 'method' => 'PUT']) !!}
Dirty way:
you may replace findOrFail() with find only and just handle it programmatically with if(!is_null($user))
Clean way:
Create a new exception file to catch your exception or just have it here within your code like so:
// Will return a ModelNotFoundException if no Course with that id
try
{
$data = Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
dd(get_class_methods($e)); // lists all available methods for exception object
dd($e);
// you might do here
session()->flash('message', ['danger', 'Oops no such course found !']);
return redirect('course'); // please mind to change it later to use names route or perhabs action()
}
And in your course index view right the following HTML to render the error
#include('errors.alert',['type'=> Session::get('message.0'),'message' => Session::get('message.1') ])
and for sure create this partial view errors/alert.blade.php:
<div class="alert alert-{{ $type }} alert-page alert-dark">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! $message !!}
</div>

Resources