I'm new to Laravel, how get the multiples tables data for filter search purpose? I already view the data like id, topic name, standard name subject name but I searching topic it show topic name only but I need whatever I search its show the full data.
This is my tables name and what I need columns (three tables are different)
1. Topics -> id, topic_name
2. Standards -> standard_name
3. subject -> subject_name
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\TopicRequest;
use App\Topic;
use App\Standard;
use App\Subject;
use DB;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
class TopicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
**/
public function index()
{
$topics = Topic::leftJoin('standards','topics.standard_id', '=', 'standards.id')->
leftJoin('subjects','topics.subject_id', '=', 'subjects.id')
->select('topics.*' ,'standards.standard_name','subjects.subject_name')
->orderBy('id', 'ASC')
->paginate(10);
return view('topic.index', compact('topics'));
}
public function create()
{
$standards = Standard::select('id','standard_name')->paginate(10);
$subjects = Subject::select('id','subject_name')->paginate(10);
return view('topic.create', compact('standards','subjects'));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'standard_id' => 'required',
'subject_id' => 'required',
]);
$topic = new Topic([
'topic_name' => $request->get('name'),
'standard_id' => $request->get('standard_id'),
'subject_id' => $request->get('subject_id'),
]);
$topic->save();
return redirect()->route('topic.index')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$topic = Topic::find($id);
$standards = Standard::select('id','standard_name')->paginate(10);
$subjects = Subject::select('id','subject_name')->paginate(10);
return view('topic.edit', compact('topic', 'id','standards','subjects'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$topic = Topic::find($id);
$topic->topic_name = $request->get('name');
$topic->standard_id = $request->get('standard_id');
$topic->subject_id = $request->get('subject_id');
$topic->save();
return redirect()->route('topic.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$topic = Topic::find($id);
$topic->delete();
return redirect()->route('topic.index')->with('success', 'Data Deleted');
}
public function search()
{
$search = Input::get('search');
$topics = Topic::where( 'id', 'LIKE', '%' . $search . '%' )->orwhere( 'topic_name', 'LIKE', '%' . $search . '%' )->paginate(10);
return view('topic.index',compact('topics'));
}
}
If the search in the tables will be independent of each other; you must list the results separately by performing a separate search on each table.
If the tables to be searched depend on the search results in other tables, you cannot do this with eloquent orm. You must type raw sql.
If this is going to be a common procedure, I suggest you search for elastic search.
Related
I was wondering on how to upload an image via API postman in Laravel and save to my database
which is phpMyAdmin. When I try to run my code in postman, this is what is showing:
"image null"
This is currently my code:
Banner CRUD Controller:
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Banner;
use Illuminate\Http\Request;
class BannerCRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$banners = Banner::all();
return response($banners,200);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$data = $request->validate([
'id'=>'required',
'web_banner_profile'=>'required',
]);
$image = $request->file('image');
if($request->hasFile('image')) {
$new_name = rand() . '.' . $image->getClientOriginalExtension();
return response()->json($new_name);
}else{
return response()->json('image null');
}
$banners = Banner::create($data);
return response ($banners, 200);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Banner Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Banner extends Model
{
public $table = "webinar";
use HasFactory;
protected $fillable = [
'id',
'web_banner_profile',
];
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create.
Hope someone can help me to get started. Thanks a lot.
You just use this code to upload an image and in postman select type file
public function store(Request $request)
{
$data = $request->validate([
'id'=>'required',
'web_banner_profile'=>'required',
]);
$image = $request->file('image');
if($request->hasFile('image')) {
$image = time() . '.' . $request->image-
>getClientOriginalExtension();
$request->image->move(public_path('Your Path'), $image);
$banner->image = 'Your Path' . $image;
return response()->json($image);
}else{
return response()->json('image null');
}
$banners = Banner::create($data);
return response ($banners, 200);
}
Replace store function with below in your BannerCRUDController.php.
Create images directory in storage.
public function store(Request $request)
{
$data = $request->validate([
'id'=>'required',
'web_banner_profile'=>'required',
]);
$image = $request->file('image');
if($request->hasFile('image')) {
$image = $request->file('image');
$destinationPath = storage_path('images');
$fileName = str_random(6) . time() . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $fileName);
$banner = new Banner();
$banner->web_banner_profile = $fileName:
$banner->save()
return response()->json($fileName);
}else{
return response()->json('image null');
}
}
Image will be uploaded in storage/images.
The error is clear request has empty image. So You should select key type file in postman
Here I am trying to store and edit the product for a specific id. Wher a user can have some product and those products can be edit for this specific user. I have tried to do this but don't know what`s the problem is happening. can someone help me. Thanks in advance
this is my ProductController.php
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Admin\StoreTagsRequest;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::latest()->paginate(20);
return view('products.index',compact('products'))
->with('i', (request()->input('page', 5) - 1) * 5);
}
function authapi(Request $request)
{
$user = User:: where('email', $request->email)->first();
if(!$user || !Hash::check($request->password, $user->password)){
return response([
'message' => ['These credentials do not match our records.']
],404);
}
$token = $user -> createToken('my-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response,201);
}
function all_app_jsons(){
return Product::all();
}
function search_by_name($name){
return Product::where('name','like','%'.$name.'%')->get();
}
function search_by_id($id){
return Product::where('id',$id)->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//$tag = Product::create($request->all());
//return redirect()->route('admin.tags.index');
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'logo' => 'required|mimes:jpeg,png,jpg,gif,svg|max:1024',
]);
$input = $request->all();
// $request->validated();
$input['user_id'] = auth()->user()->id;
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}
Product::create($input);
return redirect()->route('products.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
// public function update(Request $request, Product $product)
public function update(Request $request, $productId)
{
$product = auth()->user()->products()->findOrFail($productId);
$request->validate([
'name' => 'required',
'detail' => 'required',
'color' => 'required'
]);
$input = $request->all();
if ($image = $request->file('image')) {
$destinationPath = 'image/';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['image'] = "$profileImage";
}else{
unset($input['image']);
}
if ($logo = $request->file('logo')) {
$destinationPath = 'logo/';
$profileLogo = date('YmdHis') . "." . $logo->getClientOriginalExtension();
$logo->move($destinationPath, $profileLogo);
$input['logo'] = "$profileLogo";
}else{
unset($input['logo']);
}
$product->update($input);
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
// function indextwo(){
// //return DB::select("select * from products");
// //DB::table('products')->orderBy('id','desc')->first();
// return Product::orderBy('id', 'DESC')->first();
// }
}
in ProductController.php $product = auth()->user()->products()->findOrFail($productId); in this line said products() id undefined
this is my model Product.php
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'detail', 'image','color','logo','user_id'
];
public function user(){
return $this->belongsTo(User::class);
}
}
This is my User.php model
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
public function products(){
return $this->hasMany(Product::class);
}
}
This is product table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users');
});
}
Note: I can store many products but not for specific users. I can store and edit product every user can access it. But I want a specific user will have some product where other user cant acess
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
I userd This on projects table
I am using Laravel 5.7 and while validating my form fields I am getting this error:
"Method App\Http\Controllers\todocontroller::validate does not exist error."
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\todo;
class todocontroller extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$todos= todo::all();
return view('todo.home',compact('todos'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('todo.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$todo = new todo;
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect('/todo');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$todo=todo::find($id);
return view('todo.show',compact('todo'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$todo=todo::find($id);
return view('todo.edit',compact('todo'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$todo = todo::find($id);
$this->validate($request,[
'body'=>'required',
'title'=>'required',
]);
$todo->body = $request->body;
$todo->title = $request->title;
$todo->updated_at = now();
$todo->save();
session()->flash('message','Updated Successfully!');
return redirect('/todo');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$todo = todo::find($id);
$todo -> delete();
session()->flash('message','Deleted Successfully!');
return redirect('/todo');
}
}
error is in this code
$this->validate($request,[
'body'=>'required',
'title'=>'required|unique:todos',
]);
but as per laravel documentation my validate method is right.
Please let me know what I am doing wrong in my controller.
I have also googled for this error but no success.
I have also tried using these lines :
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Validator;
But no success. Please help me since i am getting this error for last 10 days. I don't understand what to do now. Your help will be appreciated. thanks.
Although other answers might contain valid alternative way, $this->validate(...) should work without any problem in your controller. But you should make sure you haven't changed anything from standard Laravel base controller.
Default controller located here looks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
As you see it contains ValidatesRequests trait and this trait provides validate method. So take a look at your app/Http/Controllers/Controller.php file and make sure it looks like this above.
$validatedData = $request->validate([
'body'=>'required',
'title'=>'required|unique:todos',
]);
$todo = new todo;
$todo->body = $request->body;
$todo->title = $request->title;
$todo->save();
return redirect('/todo');
If the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.
Check Writing The Validation Logic in docs again.
Try this :
use Validator;
....
....
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
link : https://laravel.com/docs/5.7/validation#automatic-redirection
I was getting an issue as I was trying to use it like this
$this->validate(request(), [
"title" => "required",
]);
Made a silly mistake there.
make sure you use your controller from right place.
use App\Http\Controllers\Controller;
I added successfully a column to previous table using MySQL database dynamically, But when I fill up the form run and send it to the the database in my local server it shows:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'forge. posts' doesn't exist (SQL: select count(*) as aggregate from ` posts` where ` slug ` = hihello)
My code of migration table 'posts'
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
for inserting a new column called 'slug' in the 'post' table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddSlugToUsers extends Migration
{
public function up(){
Schema::table('posts',function(Blueprint $table){
$table->string('slug')->unique()->after('title');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(){
Schema::table('posts',function(Blueprint $table){
$table->dropColumn('slug');
});
}
}
Successfully inserted 'slug' column but problem is posting the form to the database.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use Session;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('id', 'desc')->paginate(10);
return view('posts.index')->withPosts($posts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('posts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug'
=>'required|min:5|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->title;
$post->body = $request->body;
$post->save();
Session::flash('success', 'The blog post was successfully
save!');
return redirect()->route('posts.show', $post->id);
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$post = Post::find($id);
return view('posts.show')->withPost($post);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
// find the post in the database and save as a var
$post = Post::find($id);
// return the view and pass in the var we previously created
return view('posts.edit')->withPost($post);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Validate the data
$this->validate($request, array(
'title' => 'required|max:255',
'slug'=>'required|alpha_dash|min:5|max:255|unique:posts,slug',
'body' => 'required'
));
// Save the data to the database
$post = Post::find($id);
$post->title = $request->input('title');
$post->title=$request->input('slug');
$post->body = $request->input('body');
$post->save();
// set flash data with success message
Session::flash('success', 'This post was successfully saved.');
// redirect with flash data to posts.show
return redirect()->route('posts.show', $post->id);
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$post = Post::find($id);
$post->delete();
//for sesssion
Session::flash('success', 'The post was successfully deleted.');
return redirect()->route('posts.index');
}
}
'forge. posts' this looks like there is a space before table name posts. Did you check your model if there is a s
i have address Book table and user table i am assigning
the many user in my address book while i am created everything is fine(ok)
but when i am editing every data back in my form without assign user .
how can i get the user in editing form ?? this is my Address Book Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\AddressRequest;
use App\Http\Requests;
use App\Models\Address;
use App\Models\User;
use App\Http\Controllers\Controller;`enter code here`
use Illuminate\Pagination\Paginator;
use Auth;
use DB;
use Session;
class AddressesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index(Request $request)
{
Session::forget('searchaddress');
$addresses = Address::orderby('company_name');
$company_name = $request->input('company_name');
if(!empty($company_name)) {
//$addresses->where('company_name','LIKE','%'.$company_name.'%');
$addresses->where('company_name','LIKE','%'.$company_name.'%');
Session::set('searchaddress', $company_name);
}
$addresses = $addresses->paginate(5);
return view('address.index',compact('addresses'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$users = User::lists('first_name','id');
return view('address.create',compact('users'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(AddressRequest $request)
{
$address = Address::create($request->all());
$firstname = Auth::user()->first_name;
$lastname = Auth::user()->last_name;
$address->created_by =$firstname." ".$lastname;
$address->users()->attach($request->input('user_list'));
$address->save();
return redirect('/addresses');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$address = Address::find($id);
return view('address.show',compact('address'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
return view('address.edit',compact('address','users'));
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update( AddressRequest $request ,$id)
{
$address = Address::findOrFail($id);
$address->update($request->all());
$address->users()->sync($request->input('user_list'));
return redirect('/addresses');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$address = Address::find($id);
$address->delete();
return redirect('/addresses');
}
}
and that is my AddressBook Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
protected $fillable = [
'created_by',
'company_name',
'phone',
'email', 'address','comment'
];
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
public function getUserListAttribute()
{
return $this->users->lists('id');
}
}
[![enter image description here][1]][1]
[1]: http://i.stack.imgur.com/D4jXQ.png
You have belongsToMany relation, so in your edit action you also should get current Address users like this
public function edit($id)
{ $users = User::lists('first_name','id');
$address = Address::findorFail($id);
$address_users = $address->users->lists('id')->toArray();
return view('address.edit',compact('address','users', 'address_users'));
}
then in your view in select you should intersect arrays of $users and $address_users to get selected options.
{!! Form::select('user_list[], $users, isset($address_users) ? $address_users : null, ['id' => 'users_list', 'class' => 'form-control', 'multiple']) !!}
to avoid
isset($address_users) ? $address_users : null
you can define empty address_users array in your create method and do it like this
$address_users