laravel 5.4 showing blank view - php

I am sending data from the controller to a view (this is a single page web app) but view's input fields are showing nothing. When I use console.log I got this (screenshot attached). My question is how do I show this data in an input field of view?
Controller
public function edit(Request $request){
$results = Student::where('id', '=', $request->id)->get();
return $results;
}
View
<form class="form_edit" action="" method="post" enctype="multipart/form-data">
{{csrf_field()}}
#if(isset($results))
#foreach ($results as $result)
<input type="hidden" id="id">
<input type="text" class="form-control" name="grn" value="{{$result->grn}}">
<input type="text" class="form-control" name="first_name" id="addItem" value="{{$result->first_name}}">
<input type="text" class="form-control" name="last_name" value="{{$result->last_name}}">
<input type="button" class="btn btn-danger" id="btn_delete" value="Delete">
<input type="reset" class="btn btn-default" id="btn_close" value="Cancel">
<input type="button" class="btn btn-primary" id="btn_update" value="Update">
#endforeach
#endif
</form>

you need to pass the data to view in laravel like this
public function edit(Request $request){
$results = Student::where('id', '=', $request->id)->get();
return view('your_view_folder.your_view_page', ["results" => $results]);
}
note : your not loading the view page

To answer your specific question: To pass data into a view, you must return the view, as #JYoThl quite correctly advises. But the data should be passed in as an array with key / value pairs, or you will get an error. (See Laravel 5.4 docs.)
So if, for example, the view file containing your form element were named "formView.blade.php" and it was located in the resources/views/ directory, you would modify your controller method as follows:
public function edit(Request $request)
{
$results = Student::where('id', '=', $request->id)->get();
return view('formView', ['results' => $results]);
}
Or alternatively...
public function edit(Request $request)
{
$results = Student::where('id', '=', $request->id)->get();
return view('formView')->with('results', $results);
}
$results is now available in your view.

There are a couple of things I could recommend. First of all you are searching for student by id which I would assume should return a single student and it is the primary key of student. Therefore you may want to use Student::find(); . Also you would probably want to build your queries for searching on the model or a abstract base model in which you could create basic searches that all the models that extend it could use. for instance:
abstract class BaseModel extends Eloquent{
protected $guarded = [
'id'
];
public $primaryKey = 'id';
public $incrementing = false;
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
$this->id = uniqid();
return $this
}
public static function getObjectById($id){
$class = get_called_class();
$results = $class::find($id);
return $results;
}
public static function getAllObjects(){
$class = get_called_class();
return $class::all();
}
}
then your student class:
class Student extends Model
{
protected $fillable = [
'name'
];
protected $table = "student";
public $incrementing = false;
/**
* Student constructor.
* #param array $attributes
*/
public function __construct($attributes = array()) {
parent::__construct($attributes); // Eloquent
// Your construct code.
// TODO split string stuff to get the rest of the attributes.
return $this;
}
}
then your controller:
class StudentController extends Controller{
public function getStudent(Request $request){
$results = Student::getObjectById($request->id);
return response()->json([
'results' => $results
]);
}
}
Your route/web.php:
Route::get('/student', 'EnumController#getStudent');
I like using my own frontend so I may use ajax to complete the request:
<body>
<div class="container">
<div id="student-list" class="well"></div>
</div>
</body>
<script>
$.ajax({
type: "GET",
url: '/student',
success: function( data ) {
results = data.results;
console.log(results);
$.each(results, function(key, value){
$('#student-list').append('<div >' + value + '</option>');
});
}
});
</script>

Related

Call to undefined function App\Http\Controllers\categories() in Laravel

Please I need help, I am working on a project in Laravel, I encounter a problem when T tried to use a pivot table in manay-to-many
In my category model Category.php, I have the function below
public function users()
{
return $this->belongsToMany(user::class);
}
In my user model User.php, I have the function below
public function authors()
{
return $this->belongsToMany(author::class);
}
In web.php, I have this
Route::post('/onboarding', 'OnboardsController#categoryUser');
In my onboarding view, I have a form:
<form action="{{ url('/onboarding') }}" method="POST">
#csrf
#foreach($categories as $category)
<div class="radio-item">
<input class="form control" name="category_id" type="checkbox" id="category_id" required>
<label for="name">{{ $category -> title }}</label>
</div>
#endforeach
<div class="form-row">
<div class="form-group col-md-12 text-center">
<button type="submit">Proceed to Authors</button>
</div>
</div>
</form>
In my OnboardsController
I have this
public function categoryUser (Request $request)
{
$user = User::findOrFail(Auth::user()->id);
$user = categories()->attach($request->input('category_id'));
return redirect ( route ('onboarding_author'));
}
This is the returned error:
Call to undefined function App\Http\Controllers\categories()
When I change the code in my controller to
$category = Category::find($request->input('category_id'));
$user = User::where('user_id', Auth::id());
$category->users()->attach($user->id);
This is the returned error:
Call to undefined function App\Http\Controllers\users()
Here is my full OnboardsController.php code
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Author;
use App\User;
use App\Category;
class OnboardsController extends Controller
{
public function index()
{
//
return view('onboarding')
->with('categories', Category::all());
}
public function author()
{
//
return view('onboarding_author')
->with('authors', Author::all());
}
public function categoryUser (Request $request)
{
dd(request('category_id'));
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect ( route ('onboarding_author'));
}
Please I am new to Laravel and I have been on this for 3 days, I don't know how to solve this. I need help.
Your problem is right here:
$user = User::findOrFail( Auth::user()->id );
$user = categories()->attach($request->input('category_id'));
^^^^^^
You are calling a method categories() on... what? on nothing. I'm assuming that you want to call the categories() method inside your User.php model. So try updating your code like this:
$user = User::findOrFail( Auth::user()->id );
$user->categories()->attach($request->input('category_id'));
^^^^^
This way, you will relate both objects.
Side notes
As I mentioned, I'm assuming that you have the categories method in your User model:
# User.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
Remember that models should be capitalized.
Also, you could improve your code getting the User directly from the Auth facade
This:
$user = User::findOrFail(Auth::user()->id);
is the equivalente of:
$user = Auth::user();
You can achieve this with the following:
public function categoryUser()
{
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect(route('onboarding_author'));
}
Here, you get the Category by the request's category_id, and attach the logged in user (using the auth() helper to get the user's id).
replace
$category->users()->attach($user->id);
return BACK()->with('message', "message!");

Delete route not getting any data Laravel 6.X

I tried changing the routes and using a specific name and several things in the action attribute but there is no way the data doesn't appear when I use the form for the delete and the dd() function on my delete route
here is what the dd shows me, no info at all
My routes:
Route::get('/home/Collections', 'CollectionController#index')->name('collection.index');
Route::get('/home/Collections/{Collection}', 'CollectionController#show')->name('collection.show');
Route::get('/home/Collections/{Collection}/edit', 'CollectionController#edit')->name('collection.edit');
Route::put('/home/Collections/{Collection}', 'CollectionController#update')->name('collection.update');
Route::get('/home/Collections/crear', 'CollectionController#create')->name('collection.create');
Route::delete('/home/Collections/{Collection}', 'CollectionController#destroy')->name('collection.destroy');
Route::post('/home/Collections', 'CollectionController#store')->name('collection.store');
My controller:
public function destroy(Collection $collection)
{
$collection->delete();
return redirect('/home'.'/Collections');
}
and my form:
#foreach ($collections as $collection)
<div id="{{$collection->id}}">
<img/>
<p>{{$collection->name}}</p>
<p>{{$collection->description}}</p>
<form action="/home/Collections/{{$collection->id}}" method="POST">
#csrf
#method('DELETE')
<input type="submit" value="ELIMINAR" class = "btn btn-outline-danger mt-2">
</form>
</div>
#endforeach
my collection model:
class Collection extends Model implements Searchable
{
protected $fillable = ['id', 'name', 'description', 'user_id', 'category_id', 'certificate_id', 'img_id'];
public function items()
{
return $this->hasMany(Item::class);
}
public function certificate()
{
return $this->hasOne(Certificate::class);
}
public function image()
{
return $this->hasOne(Image::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function getSearchResult(): SearchResult
{
$url = route('collection.show', $this->id);
return new SearchResult(
$this,
$this->name,
$url
);
}
}
Problem solved a while ago, i forgot to reply to this post.
Solved it changing the Routes URL so they dont match, it seems there was a problem with them even tho it was working like exposed on another project.

Dropdown list in Laravel is not displaying

Below my drop-down list is not displaying and I don't know where the problem is. Could it be in my SerieController? I want to create an edit/update system but I've had no success.
SerieController
public function edit($id)
{
$series = Serie::with('marks')->find($id);
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series = Serie::with('marks')->find($id);
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
Mark Model
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series()
{
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Serie Model
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks()
{
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
I have another question. In my view, I have a form. Is the edit ok?
serie.index.blade
<form method="POST" action="{{ route('series.destroy', $serie) }}">
<a class="btn btn-sm btn-warning" href="{{ route('series.edit', $serie->id) }}">Editer</a>
</form>
I think it should be the other way: mark model belongsTo and Series model HasMany, no?

Two models for one Controller in Laravel (methods Edit & Update)

Would you please let me know if this controller SerieController is correct? As I don't think so.
There are two models in fact. One Model is Serie and the other is Mark.
When, I click on the drop down list, I don't see my items...
public function edit($id)
{
$series = Serie::with('marks')->find($id);
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series = Serie::with('marks')->find($id);
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
My edit.blade.php
<form class="panel-body" action="{{route('series.update',$series->id)}}" method="POST">
<input name="_method" type="hidden" value="PATCH">
#csrf
<fieldset class="form-group">
<label for="form-group-input-1">Name</label>
<input type="text" name="name" class="form-control" id="form-group-input-1" value="{{$series->name}}">
</fieldset>
<div class="form-group">
<label for="company-content">Select Mark</label>
<select name="fk_mark" id="" class="form-control">
#foreach($series->marks as $mark)
<option value="{{$mark['id']}}">{{$mark['name_mark']}}</option>
#endforeach
</select>
</div>
Concerning the model
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
public function cars(){
return $this->hasMany('App\Car','fk_serie');
}
}
Thank you in advance.
In your edit function you have to do this:
public function edit($id)
{
$series = Serie::with('marks')->find($id);
return view('admin.series.edit', compact('series'));
}
and in your blade you will fetch the marks like this:
$series->marks->name_mark;
and it is the same method for update function to update two tables data.
I hope it would helpful.
First of all: Which version of Laravel do you use?
Check out route model binding which would compact your functions like this:
public function edit(Serie $serie)
{
$series->load('marks');
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, Serie $serie)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series->load('marks');
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
Further tipps for debugging:
Set 'debug' => true in your app.php
Try to use dd($serie); to see what happens to your model.
Install debugbar: composer require barryvdh/laravel-debugbar --dev
Check your database tables to see if your code successfully created the data.
Write Unit/Feature Test to validate your application logic
Provide more data in your next SO question like sql schema, error messages etc
Without the sql schema and exact problem you're facing it's very hard to debug someone else code. I hope this helps nonetheless.
Edits: grammar, spelling and last sentence fixed/added

Items filter laravel eloquent

What is the best way to implement the items filter functionality?
I have a table with some items, and each item has some fields.
How can I select items with fields filtering, like e-commerce filtering, using Laravel 5 and Eloquent?
I've always used eloquent scopes to filter eloquent results: https://laravel.com/docs/5.1/eloquent#query-scopes
Your Controller:
use App\Item;
class ItemController extends Controller
{
public function index(Request $request)
{
$items = Item::name($request->name)->price($request->price)->paginate(25);
return view('items.index', compact('items'));
}
}
Your Model:
class Item extends Model
{
public function scopeName($query, $name)
{
if (!is_null($name)) {
return $query->where('name', 'like', '%'.$name.'%');
}
return $query;
}
public function scopePrice($query, $price)
{
if (!is_null($price)) {
return $query->where(compact('price'));
}
return $query;
}
}
Your View:
<form action="{{ route('items.index') }}" method="get">
<input type="text" name="price" />
<input type="text" name="name" />
<input type="submit" value="Search">
</form>
#foreach($items as $item)
{{ $item->name }}
#endforeach
{!! $items->render() !!}
In your scopes, you can check if the given value is null before limiting your query results. This effectively allows users to search and filter paginated results.
You could further enhance the search by automatic validation using Laravel's Form Requests so you can sure that the input they are searching for matches the data type for your query.
Keep in mind you'll have to modify the getRedirectUrl() method since your users will be executing a GET request and by default the getRedirectUrl() will contain the GET URL parameters resulting in an infinite loop since the one of the params failed validation.
Here's an example using the above:
class ItemSearchRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'nullable|string|min:2|max:100',
'price' => 'nullable|numeric',
];
}
protected function getRedirectUrl()
{
return url('/items');
}
}
I wrote a package for exactly this here: https://github.com/Tucker-Eric/EloquentFilter
It allows you to do something like:
use App\Item;
class ItemController extends Controller
{
public function index(Request $request)
{
$items = Item::filter($request->all())->paginateFilter(25);
return view('items.index', compact('items'));
}
}
You can use this awesome laravel package:
github.com/abdrzakoxa/laravel-eloquent-filter
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index(Request $request)
{
$users = Item::filter($request->all())->paginateFilter(10);
return view('users.index', compact('users'));
}
}
You can use package for regular index workflow to filter, sort, search and paginate
https://packagist.org/packages/abyss403/request-meta
class UserController extends Controller
{
...
public function index(Request $request){
// Define model
$model = new User();
// Obtain collection based on request metadata
$collection = \RequestMeta::load($model, $request)->data();
// And just return it
return $collection;
// OR using resources
return new UserResourceCollection($collection);
}
...
}
That's it

Categories