Laravel: Undefined variable after a post action - laravel

I'm making profile edit page and I had a problem after post action.
Routes file is
Route::get('profile', 'ProfileController#profile')->name('profile');
Route::post('profile', 'ProfileController#update');
Profile page Controller
public function profile()
{
$cities = City::all();
$current_city = Auth::user()->city;
$current_city_name = City::cityName($current_city);
return view('profile.edit', compact('cities', 'current_city', 'current_city_name'));
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|string|email|max:255',
]);
}
public function update(Request $request)
{
$this->validator($request->all())->validate();
$user = Auth::user();
$user->email = $request->input('email');
$user->city = $request->input('city');
$user->save();
$request->session()->flash('message', 'Information successfully changed');
return view('profile.edit');
}
And finally blade template code
<select name="city" id="city" class="form-control">
<option value="{{ $current_city }}">{{ $current_city_name }}</option>
#foreach ($cities as $city)
<option value="{{ $city->id }}">{{ $city->name }}</option>
#endforeach
</select>
First entrance on profile page is ok. But after form submitting I have an error
Undefined variable: current_city (View: C:\OSPanel\domains\ang\laravel\resources\views\profile\edit.blade.php)

You're not passing any variables to the view in your update() method, but returning the same view (that expects those variables) here:
public function update(Request $request)
{
// ...
return view('profile.edit');
}
You could simply redirect back:
public function update(Request $request)
{
// ...
return back();
}

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();

Laravel Excel : error Resource interpreted as Document but transferred with MIME

Laravel Excel to export data will download empty data with only headers in excel sheet! I want to export only the filtered data from my search using excel but it will download an empty excel sheet only with headers!! please can anyone tell me where is my error!
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
{
use Exportable;
protected $name;
protected $email;
protected $mobile_no;
protected $city;
public function __construct( $name, $email, $mobile_no , $city)
{
$this->name = $name;
$this->email = $email;
$this->mobile_no = $mobile_no;
$this->city = $city;
}
//function select data from database
public function collection()
{
return Dealer::select()->where('name', $this->name)
->where('email', $this->email)
->where('mobile_no', $this->mobile_no)
->where('city', '=', $this->city) //i tried using the above and this also same result
->get();
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event) {
$cellRange = 'A1:W1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(12);
},
];
}
//function header in excel
public function headings(): array
{
return [
'No',
'name',
'email',
'mobile_no',
'shop_name',
'city',
'address'
];
}
}
my controller
public function index(Request $request)
{
$method = $request->method();
if ($request->isMethod('get')) {
$name = $request->name;
$email = $request->email;
$city = $request->city;
$mobile_no = $request->mobile_no;
if ($request->has('search')) {
$dealers = Dealer::where('name', 'LIKE', '%'.$name.'%')
->where('email', 'LIKE', '%'.$email.'%')
->where('mobile_no', 'LIKE', '%'.$mobile_no.'%')
->where('city', 'LIKE', '%'.$city.'%')
->paginate(5);
return view('dealer.index', compact('dealers'));
}
elseif ($request->has('exportSearchExcel')) {
return Excel::download(new DealersSearchExport($name ?? '', $email ?? '', $mobile_no ?? '', $city ?? ''), 'DealersSearchExcel-reports.xlsx');
}
else{
$dealers = Dealer::orderBy('id', 'DESC')->paginate(5);
return view('dealer.index', compact('dealers'));
}
}
}
blade
<form action="{{ route('dealer.index') }}" method="GET" enctype="multipart/form-data">
#csrf
<div class="form-group row">
<div class="col-sm-3">
<label for="name">Name: </label>
<input class="form-control" name="name" value="{{ request()->input('name') }}" type="text" placeholder="The Dealer Name">
</div>
.....................................................................
</div>
<div class="col-md-12 pt-3 text-right">
<button type="submit" name="search" class="btn btn-primary"><i class="fa fa-fw fa-search"></i> Search</button>
<button type="submit" name="exportSearchExcel" class="btn btn-secondary text-light"><i class="fa fa-download"></i> Export Excel </button>
</div>
</div>
No error is showing just in my console it will return this error and download an empty xslx whenever I press the export button.
Resource interpreted as Document but transferred with MIME type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: "http://127.0.0.1:8000/dealer?_token=TTlpqFNn4hr5rwI1jSlt0d4mbtww2moO8i1WWjfn&name=&email=&mobile_no=&exportSearchExcel=".
Update
I fixed it by changing my query in DealerExportSearch.php to the same query that I have in controller then it worked
DealerExportSearch.php
class DealersSearchExport implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents , WithMapping
{
//the above codes not changed till the collection function
//function select data from database
public function Collection()
{
return Dealer::where('name', 'LIKE', '%'.$this->name.'%')
->where('email', 'LIKE', '%'.$this->email.'%')
->where('mobile_no', 'LIKE', '%'.$this->mobile_no.'%')
->where('city', 'LIKE', '%'.$this->city.'%')
->get();
}
public function map($row): array{
$fields = [
$row->id,
$row->name,
$row->gender,
$row->date_of_birth,
$row->email,
$row->mobile_no,
$row->shop_name,
$row->city,
$row->address,
];
return $fields;
}
///below codes not changed .....

How can I get value from a select field?

I have a livewire CRUD component to make posts. It worked perfectly before I tried to add a choice of categories. This is a piece of code, where I try to choose a category:
<select class="form-select" aria-label="Default select example">
<option wire:model="category_id" selected>Выберите категорию</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">
{{ $category->name }}
</option>
#endforeach
#error('category_id') <span class="text-red-500">{{ $message }}</span>#enderror
</select>
I can display all the categories and choose one, but I can't get it in the component. I have tried to use a checkbox element. I was even validated, whenever I chose a category or not. The select field isn't validated at all. I can just output all the categories from the db.
Here is my CRUD component.
<?php
namespace App\Http\Livewire;
use App\Models\Category;
use Livewire\Component;
use App\Models\Post;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class Posts extends Component
{
public $title, $categories, $category_id, $body, $post_id, $search, $img;
public $isOpen = 0;
use WithFileUploads;
use WithPagination;
public function mount()
{
$this->categories = Category::all();
}
public function render()
{
$search = '%' . $this->search . '%';
$posts = Post::where('title', 'LIKE', $search)
->orWhere('body', 'LIKE', $search)
->latest()
->paginate(5);
return view('livewire.posts.posts', ['posts' => $posts])->layout('layouts.app');
}
public function create()
{
$this->resetInputFields();
$this->openModal();
}
public function openModal()
{
$this->isOpen = true;
}
public function closeModal()
{
$this->isOpen = false;
}
private function resetInputFields()
{
$this->category_id = '';
$this->title = '';
$this->body = '';
$this->post_id = '';
}
public function store()
{
$this->validate([
'category_id' => 'required',
'title' => 'required',
'body' => 'required',
'img' => 'image|max:1024'
]);
Post::updateOrCreate(
['id' => $this->post_id],
['category_id' => $this->category_id,
'title' => $this->title,
'body' => $this->body,
'img' => $this->img->hashName(),
]);
if(!empty($this->img)) {
$this->img->store('public/docs');
}
session()->flash('message',
$this->post_id ? 'Пост успешно обновлен.' : 'Пост успешно создан.');
$this->closeModal();
$this->resetInputFields();
}
public function edit($id)
{
$post = Post::findOrFail($id);
$this->category_id = $post->category_id;
$this->post_id = $id;
$this->title = $post->title;
$this->body = $post->body;
$this->img = $post->img;
$this->openModal();
}
public function delete($id)
{
Post::find($id)->delete();
session()->flash('message', 'Пост успешно удален.');
}
}
Will setting a name for select solve the problem?
<select class="form-select" aria-label="Default select example" name="category_id">
<option wire:model="category_id" selected>Выберите категорию</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">
{{ $category->name }}
</option>
#endforeach
#error('category_id') <span class="text-red-500">{{ $message }}</span>#enderror
</select>
Currently it doesn't seems like framework can identify the name for this input

Laravel: IF statement drop down list

So i currently have a drop down list where it will output a list of hotels based on its price. I now want to further develop the drop down list so that it can output a list of hotels based on price AND distance. How would i exactly create a drop down list that will output a list of hotels based on 2 or more criteria.
SearchController.php
public function index(Request $request)
{
$distances = DB::table('posts')->select('distance')->distinct()->get()->pluck('distance');
$prices = DB::table('posts')->select('price')->distinct()->get()->pluck('price');
$postsInRange = $request->has('distance')
? Post::where('distance', $request->distance)->get()
: [];
$postsInRange1 = $request->has('price')
? Post::where('price', $request->price)->get()
: [];
return view('Pages.search', [
'distances' => $distances,
'prices' => $prices,
'posts' => $postsInRange,
'posts' => $postsInRange1,
]);
}
public function store(Request $request)
{
// This will return all request data to your screen.
return $request->all();
return view('Pages.search');
}
Search.blade.php
<select name="distance" id="distance" class="form-control input-lg dynamic" data-dependent="state">
<option value="">Distance</option>
#foreach($distances as $distance)
<option value="{{ $distance }}">{{ $distance }}</option>
#endforeach
</select>
<br>
<select name="price" id="price" class="form-control input-lg dynamic" data-dependent="state">
<option value="">Price</option>
#foreach($prices as $price)
<option value="{{ $price}}">{{ $price}}</option>
#endforeach
So to clarify the drop down list works but only outputs one of the choices selected.
I think what you need is query filter
$post = new Post;
if ($request->has('price')) {
$post->where('price', $request->price);
}
if ($request->has('distance')) {
$post->where('distance', $request->distance);
}
return view('Pages.search', [
'distances' => $distances,
'prices' => $prices,
'posts' => $post->get()
]);
I assume that you need one list applying both filters.

undefined variable Posts

I am trying to complete a search filter feature for my website however i am recieving the following error:
Undefined variable: posts (View:
#foreach($posts as $distance)
<option value="{{$distance->distance}}">{{ $distance->distance}}</option>
#endforeach
Here is my search.blade.php (error occuring:
#foreach($posts as $distance)
<option value="{{$distance->distance}}">{{ $distance->distance}}</option>
#endforeach
</select>
SearchController.php
function index()
{
$posts = DB::table('posts')
->groupBy('title')
->get();
return view('posts.search')->with('posts', $posts);
}
Does anyone know why i am receiving the error even thoough my posts have been defined.
In your Controller
public function index()
{
$posts = DB::table('posts')
->groupBy('title')
->get();
return view('posts.search',compact('posts'));
}
In your model
#foreach($posts as $distance)
<option value="{{$distance->id}}">{{ $distance->distance}}</option>
#endforeach

Resources