Laravel user input form to query database - laravel

been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.
perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$pstoreNum = request('pstoreNum');
$result = perfumes::where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
}
public function perfWeekSearch()
{
$weekNum = request('perfWeekNum');
$result = perfumes::where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
Route::get('/perfumes', 'perfumescontroller#index');
Route::get('/perfumes', 'perfumescontroller#perfWeekSearch');
Blade:
<form action="perfumes" method="get">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" name="perfWeekNum" placeholder="Type in Store Number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
Do i need to use some sort of check if not null method? or is there an easier way??
Thanks

I think this would be work below is your perfumes controller
class perfumescontroller extends Controller
{
public function index()
{
$data = $request->all();
if(!empty($data['pstoreNum'])){
$pstoreNum = $data['pstoreNum'];
$result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
->get();
return view('perfumes',compact('result'));
} else if(!empty($data['perfWeekNum'])){
$weekNum = $data['perfWeekNum'];
$result = DB::table('perfumes')->where('WeekNumber','=',$weekNum)
->get();
return view('perfumes',compact('result'));
}
}
}
and you use any with route like below:
Route::any('/perfumes', 'perfumescontroller#index');

Related

Call to a member function comments() on null when use foreign key

This is error Call to a member function comments() on null, in model give a relation still show this error
Article model
function user() {
return $this->belongsTo(User::class, 'id');
}
public function comments()
{
return $this->hasMany(Comment::class, 'id');
}
Comment Model
public function user()
{
return $this->belongsTo(User::class);
}
public function article()
{
return $this->belongsTo('App\Article');
}
This is contoller
public function store(Request $request)
{
//dd($request->all());
Auth::user();
$comment = new Comment;
$comment -> user_id=Auth::user()->id;
$comment-> comment = $request->get('comment');
$article = Article::find($request->article_id);
$article->comments()->save($comment);
return redirect()->back()->with('success', 'your comment,successfully save');
}
This is blade file
<form method="post" action="{{ route('comment.store') }}">
#csrf
<div class="form-group">
<textarea class="form-control" name="comment"></textarea>
<input type="hidden" name="article_id"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Add Comment" />
</div>
</form>
You need to set a value for the hidden field.
<input type="hidden" name="article_id" value="{{ $article->id }}"/>
Secondly for easier debugging these errors, using findOrFail() will ensure your app blows up, with a proper error message. Instead of just returning null.
$article = Article::findOrFail($request->article_id);
EDIT
You are also mixing two saving approaches together, either you associate the article to the comment or create a new comment. This is the approach i like to use.
$comment = new Comment;
$comment->user_id = Auth::user()->id;
$comment->comment = $request->get('comment');
$article = Article::find($request->article_id);
$comment->article()->associate($article);
$comment->save();

How to send variable from blade to controller without changing the url

In blade I have a list of books. I want to choose a specific book to show its information. And to do so I want to send with href the id of the book to my controller passing through route.
For example i have
<div class="body text-center">
<h6><b>{{($book->getName())}}</b></h6>
</div>
In href I want to add $bookId = $book->id and the route name so I can call the route with the specific name which calls a method in a controller which can use the variable $bookId
Route::get('/infromation','Books\BookController#index')->name('info');
Here's two propositions:
The first one is to use spatie/laravel-sluggable to have the book name in the URL
The second one is to access the book without changing the URL with a POST request
Using spatie/laravel-sluggable
The slug will be generated automatically from name when the book is created.
your-migration.php
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('slug')->unique()->index();
$table->string('name');
// ...
$table->timestamps();
});
web.php
// Change the URIs as you want. `{book}` is mandatory to retrieve the book though.
Route::get('/books','Books\BookController#index')->name('book.index');
Route::get('/books/{book}','Books\BookController#show')->name('book.show');
Book.php
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Book extends Model
{
use HasSlug;
protected $guarded = [];
public function getSlugOptions()
{
// Adapt with what you want
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
}
public function getRouteKeyName()
{
return 'slug';
}
}
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show(Book $book)
{
// $book is retrieving using Model Binding: https://laravel.com/docs/5.8/routing#route-model-binding
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<a href="{{ route('book.show', $book) }}">
<h6><b>{{ $book->getName() }}</b></h6>
</a>
</div>
Using POST request (URI does not change) and without SLUG
I wouldn't recommend using this for the user experience.
The user cannot bookmark the book or share the link with someone else
When refreshing the page, it will prompt to the user if he want to re-submit the form request
web.php
Route::get('/books','Books\BookController#index')->name('book.index');
Route::post('/books','Books\BookController#show')->name('book.show');
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show()
{
$book = Book::findOrFail(request('book_id'));
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<form action="{{ route('book.show') }}" method="POST">
#csrf
<input type="hidden" value="{{ $book->id }}" name="book_id">
<h6>
<button type="submit">
<b>{{ $book->getName() }}</b>
</button>
</h6>
</form>
</div>
You can remove the default button style to make it looks like a link
https://stackoverflow.com/a/45890842/8068675
You can try like this
<form action="/BookName/information/<?php echo $book->id; ?>" method="post">
<div class="body text-center">
<input type="hidden" name="book_id" value="{{ $book->id }}">
<a href="/information/<?php echo $book->id; ?>">
<button type="submit" name="book_information" class="btn btn-primary">
<h6>
<b>{{($book->getName())}}</b>
</h6>
</button>
</div>
</form>
// make route like this
Route::post('/BookName/information/{id}','Books\BookController#index');
// Access the that id in controller
public function index(Request $request)
{
echo $request->book_id;
}

Laravel Maatwebsite excel

I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
its simple on mattwebsite you need a controller like below :
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
$data['title'] = $row['title'];
$data['description'] = $row['description'];
$data['fax'] = $row['fax'];
$data['adrress1'] = $row['adrress1'];
$data['telephone1'] = $row['telephone1'];
$data['client_type'] = $row['client_type'];
if (!empty($data)) {
DB::table('clients')->insert($data);
}
}
});
}
Session::put('success on import');
return back();
}
and a view like this :
<form
action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-lg-2">excel import</label>
<div class="col-lg-10">
<div class="uploader"><input type="file" name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
</div>
</div>
<button class="btn btn-primary">submit</button>
</form>
and finally a route like below :
Route::post('admin/client/importExcel', 'ClientController#importExcel');

Laravel search feature without using collective for forms

I'm trying to use a basic html form without using Laravel collective.
I have this code here.
<form class="form-inline my-2 my-lg-0" action="{{route('patients.index')}}" method="get">
<input class="form-control mr-sm-2" type="text" placeholder="Search" name="search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
And then in the PatientsController index function
public function index()
{
$search = \Request::get('search');
$patients = Patient::where('lname','like', '%'.$search.'%');
return view('/searchResults')->with('patients', $patients);
}
When i return the view at the end of the function, it just loads a blank page. when i do $patients = Patient::all(), it yields my full database so i know that at least part of the query is right. what am i doing wrong?
Try searchResults without /
public function index()
{
$search = \Request::get('search');
$patients = Patient::where('lname','like', '%'.$search.'%')->get();
return view('searchResults', ['patients'=>$patients]);
}
You blade template:
resources/views/searchResults.blade.php

how to Pass array from view to controller in Laravel?

I make a form in blade.php, Here I can select multiple checkbox, and I want to pass selected input’s value to controller in a array.But I failed, I can not send the data.
Here is code from view. The selected input’s value can be 1,2 etc;
<form method="post" action="{{action('votesubmitController#votesubmit')}}" class="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
#foreach($candidate_list[$post_list->id] as $candidate_list[$post_list->id])
<li>
<input type="checkbox" name= "selected[]" value= {{
$candidate_list[$post_list->id]->id }}>
<label>
<!-- some code here -->
</label>
</li>
#endforeach
<button type="submit" id="login-button">Submit</button>
</form>
Here is route-
Route::post('/votesubmit','votesubmitController#votesubmit');
If I write return $input in controller I find –
{"_token":"TQIUxVz0LjzM84Z7TaUPk3Y7BLZPjmXUyhXhlQfp","selected":
["1","2"]}
That’s I need. I do not know how to get selected value. When I get specific route error exception happens . and says "Undefined variable: selected".
Here is my Controller’s code-
class votesubmitController extends Controller
{
public function votesubmit()
{
$input = Input::all();
// return $input;
foreach ($selected as $selected) {
echo $selected;
}
}
}
// You can try this
class votesubmitController extends Controller
{
public function votesubmit()
{
//$input = Input::all();
//$selected = $input['selected'];
$selected = Input::get('selected');
foreach ($selected as $selected)
{
echo $selected;
}
}
}
Either use
$selected = $input['selected']
Or
pass it using Ajax.

Resources