I have a search box in my views and I want to search foods from the database.
My view for seach box is:
<div class="field" id="searchform">
<input type="text" id="searchterm" placeholder="e.g mutton
karahi,pizza..." />
<button type="button" id="search"
onclick="window.location='http://localhost:8000/search'">Find Food!</button>
</div>
My food table has fields like:
Food_id
FoodName
FoodDescription
FoodImage
Price
Now I want to search my foods By name.How I can do that?plz help me.I am new to laravel and I am using laravel 5.2.
Search In Laravel
Create Your Model
As you mentioned you have a table say food we will generate a model Food.php in your app folder
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Food extends Model {
use SoftDeletes;
protected $table = 'food';
protected $fillable = ['id','name','description','image'];
protected $dates = ['deleted_at'];
}
Crete a search Controller
php artisan make:controller SearchController
Inside Controller Write logic to retrive your model records based on food name
public function search(Request $request){
$foods = Food::where('name','%LIKE%',$request->input('q'))->get();
return view('search')->with(['foods'=>$foods]);
}
We are now returning our modals to view. You can use dd($foods) either in your controller or in view to check the results
In your Search Form View, make action to SearchController
{{Form::open(array('action' => 'SearchController#search','method'=>'post','name'=>'mini_search','id'=>'mini_search','role'=>'form')) }}
<div class="field" >
<input type="text" id="searchterm" placeholder="e.g mutton
karahi,pizza..." name="q" />
<button type="submit" id="search" >Find Food!</button>
</div>
{{Form::close()}}
Finally, we also need a view to display our results
SO create a file search.blade.php and display the results.
https://laravel.com/docs/5.2/views#passing-data-to-views
<ul>
#foreach($foods as $food)
<li>{{$food->name}}</li>
#endforeach
</ul></pre>
Presumably, your table name is foods, you can do this with Eloquent or DB facade in your controller.
public function search(){
$foodName = Input::get('food_name'');
$foods = Food::where('FoodName', $foodName)->get();
return $foods;
}
This is most simple version. I hope it can help.
Related
I have many to many relationship between UserProfile model and UserTv model. Here are the tables.
user_profiles
id user_id username
1 1 AuthUser
tv
id name
1 Action
2 Drama
3 Comedy
4 manually added some genre from input from authenticated user
user_tv
id user_id tv_id
1 1 2
1 1 4
For example, these first three ids in tv table (Action, Drama, Comedy) are inserted through seeders and this fourth id is inserted manually through input text from form by that user who is authenticated. And there lies the my problem. I want that those values that are manually added through input in form to only be able to see that user that inserted those values, and all other users can't. But also I want all users to remain to see those first three values that are generated through seeder. Currently everything works so that all users can see everything. Any help is appreciated. Here is my code.
UserProfile.php
<?php
namespace App;
use App\User;
use Illuminate\Support\Facades\App;
use Illuminate\Database\Eloquent\Model;
class UserProfile extends Model
{
protected $fillable = [
'user_id',
'username',
];
public function user()
{
return $this->belongsTo(User::class);
}
public function tvs()
{
return $this->belongsToMany(UserTv::class, 'user_tv', 'user_id', 'tv_id');
}
}
UserTv.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserTv extends Model
{
protected $table = 'tv';
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_tv', 'tv_id', 'user_id');
}
}
web.php
Route::get('profile/{profile}', 'UserProfileController#showProfile')->name('profile.show');
Route::patch('profile/update-tv-options', 'TvController#updateTvOptions')->name('profile.update.tv.options');
Route::post('profile/insert-tv-options', 'TvController#insertTvOptions')->name('profile.insert.tv.options');
TvController.php
<?php
namespace App\Http\Controllers;
use App\UserTv;
use App\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\InsertTvOptionsRequest;
use App\Http\Requests\UpdateTvOptionsRequest;
class TvController extends Controller
{
public function updateTvOptions(UpdateTvOptionsRequest $request)
{
$user = Auth::user();
$userProfile = UserProfile::where('user_id', Auth::id())->first();
$userProfile->update($request->all());
$data = $request->get('tvsOptions', '[]');
$userProfile->tvs()->sync($data);
return redirect()->route('profile.show', [$user->username]);
}
public function insertTvOptions(InsertTvOptionsRequest $request)
{
$user = Auth::user();
$tv = UserTv::create($request->all());
return redirect()->route('profile.show', [$user->username]);
}
}
UserProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use App\UserTv;
use App\UserProfile;
class UserProfileController extends Controller
{
public function showProfile($username, Request $request)
{
$profileId = User::getIdFromUsername($username);
$userForShowProfile = User::with('userProfile')->where('id', $profileId)->firstOrFail();
$tvsOptions = UserTv::get();
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs()->get();
return view('profile.show', compact('userForShowProfile', 'tvsOptions', 'userTvsOptions'));
}
}
show.blade.php
<section data-edit="movies" class="editMovies">
<h3 class="textBold">Film</h3>
<form action="{{ route('profile.update.tv.options') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group flex">
#isset($tvsOptions, $userTvsOptions)
#foreach($tvsOptions as $option)
<div class="interestedIn">
<input type="checkbox" name="tvsOptions[]" value="{{ $option->id }}" {{ $userTvsOptions->contains('id', $option->id)? 'checked': ''}}>
<label for="">{{ $option->name }}</label>
</div>
#endforeach
#endisset
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR CHECKBOX</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
<form action="{{ route('profile.insert.tv.options') }}" method="POST" class="flex">
#csrf
<div class="form-group mt-5">
<input type="text" name="name" placeholder="INSERT NEW MOVIE GENRE">
</div>
<div class="form-group">
<label for="" class="textBold">Button FOR INSERT!!!</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
</section>
And I want to contain first three options for all users and that fourth option for only this user that inserted that.
Something like this?
$defaultTvsOptions = UserTv::whereIn('name', ['Action', 'Drama', 'Comedy'])->get(); // return only action, drama and comedy. you can use ids.
$userTvsOptions = UserProfile::findOrFail($profileId)->tvs;
$tvsOptions = $defaultTvsOptions->merge($userTvsOptions); // merge default and logged user tvs options
To make it more maintainable, you could use configs in your root directory of project.
$defaultTvsOptions = UserTv::whereIn('name', config('config name where return the array'));
Hope it helps you.
Hey As you Have a pivot table You can pull the data Like This:
Userprofile model
public function tv() {
return $this->hasManyThrough(
'Tv class ',
'user_tv class',
'user_id',
'id',
'user_id',
'tv_id'
);
}
UserController
$data = UserProfile::with('tv')
->where(condition)
->get();
At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you
I am trying to insert data into a database. This actually works but whenever the submit button is clicked and the browser goes to the action page, i get a "CLI has stopped working" error resulting in a shut down of the local php server.
Since i have no clue as to why i am getting this problem. I will provide all the code that possibly could lead to this error.
The form:
<form method="POST" action="store">
{{ csrf_field() }}
<label for="title">Title</label>
<input type="text" id="title" name="title">
<label for="url">URL</label>
<input type="text" id="url" name="url">
<input type="submit">
</form>
The controller:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AddArticle extends Controller
{
...
public function store(Request $request)
{
$article = new Article;
$article->title = $request->title;
$article->url = $request->url;
$article->save();
}
...
The model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $table = "posts";
protected $fillable = [
'title',
'url',
];
}
The web.php route:
Route::post('/store', 'AddArticle#store');
When the browser goes to /store, i get this CLI stopped working error.
Kind regards
code of message model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Message extends Model
{
protected $table="Message";
}
code of user model
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
protected $table="NewUser";
}
The message is not displayed because you didn't include it to your blade template. The working solution should be like this:
<img src="\upload\{{$detail->image}}" height="100px" width="100px">
{{$detail->username}}
<br/>
{{$detail->email}}
<br>
#foreach($messages as $message)
{{$message->body}}
#endforeach
<form action="/store/{{$detail->id}}" method="post">
{!!csrf_field()!!}
<input type="text" name="title" class="form-control" placeholder="title" required>
<br/>
<textarea rows="4" cols="4" name="post" class="form-control" placeholder="post" required></textarea>
<br/>
<input type="submit" name="submit" class="btn btn-primary" value="submit">
</form>
Of course change "body" with whatever field you have in messsages table in DB.
EDIT:
You are forwarding same ID to fetch users and their messages.
public function getId($id)
{
$data['detail']=User::find($id) AND $data['messages']=Message::find($id);
return view('new_form',$data);
}
Once you define the right model relationship, you should do something like this:
public function getId($id)
{
$user = User::find($id)
$data['detail']=$user AND $data['messages']=$user->messages()
return view('new_form',$data);
}
Your User.php should have the relationship as Ketav Chotaliya suggested:
public function messages()
{
return $this->hasMany('App\Message');
}
This should work if your message model is called Message.php, for everything else, rewrite accordingly
I'm not getting your point exactly.
If you are facing problem in JOIN two tables than here is the solution.
You can directly get JOINED data without JOIN Query IF you set eloquent-relationships in model..
Model file
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class <model_name> extends Model
{
public function <function_name>()
{
return $this->hasMany('<namespace_of_target_model>');
}
}
Get JOINED Data in one single query.
$data = DB::table('table')
->where('column', <condition>)
->get();
If you didn't set relationship between models than you have to manually JOIN two tables.
Controller file
$data = DB::table('<table_1>')
->leftJoin('<table2>', '<table_1.key>', '<condition>', '<table_2.key>')
->get();
Here is the Example of different types JOIN in Laravel 5.3.
I am trying to delete data from my table employes by getting the id of the data and transferring it by using get route but i get the following error
ModelNotFoundException in Builder.php line 125: No query results for
model [App\employe].
her is my route
Route::get('/delete/{employe}', 'EmployeController#delete');
Route::post('/delete', 'EmployeController#handleDelete');
and i have model called employe to access my table
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class employe extends Model {
protected $fillable = array('fname','lname','age','sex','phone','email','houseno','city','kebele','state','username','password','workposition','salary','bankaccount','bankname','contactid','employedate');
}
part of my controller for deleting
public function delete(employe $employe)
{
// Show delete confirmation page.
return View('deleteemploye', compact('employe'));
}
public function handleDelete()
{
$employe = employe::findOrFail(Input::get('employe'));
$employe->delete();
return Redirect::action('EmployeController#index');
}
her is my view for deleting file
#extends('app')
#section('content')
<div class="page-header">
<h2>Delete {{$employe->fname}} Are you sure?</h2>
</div>
<form action="{{ action('EmployeController#handleDelete') }}" method="post" role="form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="employe" id="employe" value="{{ $employe->id }}" />
<input type="submit" class="btn btn-default" value="Yes" />
No
</form>
#stop
Looks like laravel cant find the model with the primary key you are passing. Check the database and see if its there. If it is check the deleted_at field. If it has a date in it, it means it is already deleted. You can still find it by using withTrashed()
$employe = employe::withTrashed()->findOrFail(Input::get('employe'));
and if you have soft deleting enabled for this model, you can completely remove the given row by running
$employe = employe::withTrashed()->findOrFail(Input::get('employe'))->forceDelete();