search bar not working using laravel livewire - laravel

here's the code for livewire whenever I run this code it shows nothing I am using laravel 7 and livewire for this approach.
For controller
<?php
namespace App\Http\Livewire;
use App\Models\brands;
use Livewire\Component;
class SearchBar extends Component
{
public $searchTerm;
public function render()
{
$searchTerm = '%'.$this->searchTerm.'%';
return view('livewire.search-bar', [
'users' => brands::where('Name', 'like', $searchTerm)->get()
]);
}
}
For view
<div>
<input type="text" placeholder="Search users..." wire:model='searchTerm'/>
<ul>
#foreach($users as $user)
<li>{{ $user->Website }}</li>
#endforeach
</ul>
</div>

I think it should actually work. but if not, this is how i would write it.
You do not need to pass the variables via the view() function.
<?php
namespace App\Http\Livewire;
use App\Models\brands;
use Livewire\Component;
class SearchBar extends Component
{
public $searchTerm;
public $users
public function render()
{
$searchTerm = '%'.$this->searchTerm.'%';
$this->users = brands::where('Name', 'like', $searchTerm)->get();
return view('livewire.search-bar');
}
}
I hope this works, otherwise maybe something is wrong with the livewire installation?

I think your issue is that you're searching your Brands model for a "Name" where database columns are typically lowercase, so you would need to use "name" instead. Unless you named the column with an uppercase, you would need to use lowercase. Here is also how I would format the Livewire Component.
<?php
namespace App\Http\Livewire;
use App\Models\Brands;
use Livewire\Component;
class SearchBar extends Component
{
public $searchTerm;
public function render() {
return view('livewire.search-bar', [
'users' => $this->users,
]);
}
public function getUsersProperty() {
$query = Brands::query()
->when($this->searchTerm, fn($query) => $query->where('name', 'like', '%'.$this->searchTerm.'%'))
->get()
return $query;
}
}
I would isolate the function to actually retrieve the Brands to another function, so it doesn't clutter your render method. Notice that I didn't declare a public $users variable. When you don't declare a variable in a component, Livewire will search for a getVariableNameProperty() function and call that. So on each render, you are calling that function without having to explicitly call it, and returning the query results to the view.
Also just a note, models are typically singular unless you explicitly create them as plural, so your Brands model could be Brand. If your model does happen to be Brand, you just need to change the Brands parts in the above code to Brand. As well, you are using a lowercase first letter on your model--that needs to be uppercase.

Related

Eloquent Relationship belongsTo Return Error In Laravel 8

Let's assume, There Is two Table 'empData' & 'district'. 'empData' table contain 'id', 'name', 'empDistrict' ('empDistrict' contain the corresponding id of district) . and 'District' table contain 'id', 'name' of all districts.
Now I want to fetch the student's details including the district name. (Note: In the empDatatable, I contain only district id) How can I achieve this?
My Implementation
My District Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\EmpData;
class District extends Model
{
protected $guarded = [];
public function empdistrict(){
return $this->belongsTo(EmpData::class, 'empDistrict', 'id');
}
}
My EmpData Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::all();
return view('frontend.allusermindata',compact(['data']));
}
My Blade file where I show the data
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict()->name}}</p>
}
But I get this error
Trying to get property 'name' of non-object
foreach($data as $user){
<p>Name : {{ $user->empName }}</p>
<p>District : {{ $user->empdistrict->name}}</p>
}
Calling the method returns a BelonsTo class instance. Use laravel magic method by calling it as an attribute.
Further on this question, you'll have performance issues down the line, better load the data in the same query.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\EmpData;
use App\Models\District;
class empDataController extends Controller
{
$data= EmpData::with('empdistrict')->get();
return view('frontend.allusermindata', compact(['data']));
}

Laravel Livewire model property binding

This is my Livewire component
<?php
namespace App\Http\Livewire\Dashboard;
use App\Models\Post;
use Livewire\Component;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class EditPost extends Component
{
use AuthorizesRequests;
public ?Post $postSingle = null;
protected $rules = [
'postSingle.priority' => 'digits_between:1,5',
];
public function setPriority(Post $postSingle, $priority)
{
$this->authorize('update', $postSingle);
$this->postSingle->priority = $priority;
}
}
In my blade view I have
<button wire:click="setPriority({{ $postSingle->id }}, 4)"></button>
and somewhere else I show the priority with {{ $postSingle->priority }}
The reason why I don't do model property binding directly with wire:model="postSingle.priority" is that I want to run $this->authorize('update', $postSingle);.
What happens with the code below is that if I click the button, $postSingle->priority in the blade view is updated, but the Post record is not updated in my database. What am I missing?
You appear to have overlooked actually saving the record.
public function setPriority(Post $postSingle, $priority)
{
$this->authorize('update', $postSingle);
$this->postSingle->priority = $priority;
// save the record
$this->postSingle->save();
}

How to architect a project which has more number of dynamic pages in laravel

I have a project which has a large number of dynamic pages. Approximately 30+ pages. The content of each page is different. what I did is created 30 tables and 30 routes as well. And on the admin side, there are 30+ modules to edit the contents. Is it the right way to do this?. In database table, different columns has to be kept.
// Route definition...
Route::get('/page1', [Page1Controller::class, 'show']);
Route::get('/page2', [Page2Controller::class, 'show']);
Route::get('/page3', [Page3Controller::class, 'show']);
// Controller method definition...
public function index() {
return view('page1');
}
// Route definition...
// All other routes above this slug catch all. otherwise it will try and hit this controller all the time and fail.
Route::get('/{slug}', [PageController::class, 'show']);
// Controller method definition...
public function show($slug)
{
$contents = PageContents::where('slug', $slug)->firstOrFail();
if ($contents) {
return view('page')->with('contents', $contents);
}
return view('404');
}
This way you have a table with all the contents you need. e.g. title, body copy so on. but if each layout is different you could also return a different view. e.g.
public function show($slug)
{
$contents = PageContents::where('slug', $slug)->firstOrFail();
if ($contents) {
return view('page-'.$slug)->with('contents', $contents);
}
return view('404');
}
You can create only one controller and add a parameter in the route(web.php):
web.php
//---Route Definition
Route::get('page/{page_number}', [PageController::class, 'show'])->name('page.show');
PageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
class PageController extends Controller {
//---Show
public function show($page_number) {
return view('show.show', compact('page_number'));
}//---End of Function show
}
If you want to retrieve your data from a database just one table is enough, just create a page table and give a field by the name of page_number and retrieve your specific page data by the given field.
For example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Crypt;
class PageController extends Controller {
//---Show
public function show($page_number) {
$page = PageContent::where('page_number', $page_number)->first();
return view('show.show', compact('page'));
}//---End of Function show
}
**
Your Link to routes
<a href="{{ route('page.show', ['page_number' => 1])) }}" class="" title="Show">
Show
</a>

Define a variable not explained

Sorry for the dumb question but can anyone please tell me how to define a variable in very simple terms? I have struggled for several months with "undefined variable" errors. Are variables stored in config? Or maybe in routes?
I have a database with a customers table. When I put this on my view home page {{$customers->name}} I get Undefined variable: customers.
Fine. So how and where do I define a variable. I would have thought it WAS defined given that the database table is literally called customers. Ugh!
My model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['name', 'phone'];
public function address()
{
return $this->hasOne(CustomerAddress::class);
}
public function purchases()
{
return $this->hasMany(CustomerPurchase::class);
}
}
Undefined variable means the variable does not exist and the reasons for your case is, you did not pass it in the view.
Usually, to get the customers records from the database to your views, you can do it in several ways:
Query it prior to loading your view then pass it to your views:
//doing it in the controller
//create a controller: php artisan make:controller CustomerController
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Customer; //Dont forget to import your Customer model
class CustomerController extends BaseController
{
public function index()
{
$customers = Customer::get(); //this will fetch the customer using your mdoel
return view('customer', ['customers' => $customers]); //this will pass the records to the view
}
}
//then in your routes/web.php:
Route::get('/customers', 'CustomerController#index'); //when you go to your application/customers in the browser, it will go to the controller and return the view with the records.
//OR you can skip the controllers and do it in the routes/web.php directly as what #jitesh jose mentioned.
Query straight into your view (Not really recommended, but sometimes you just need to make it work)
In your customer.blade.php
#php
$customers = \App\Customer::get();
#endphp
<ul>
#foreach($customers as $customer)
<li>{{$customer->name}}</li>
#endforeach
</ul>
My advice, try to watch a few basic Laravel videos so that you will understand the flow of the request and response.
If your model name is Customer,laravel automatically pick the table name as customers.Otherwise you have to use your desired table name in Model as follows.
protected $table = 'customers_table';
In your web.php
Route::get('/home',function () {
$customers = DB::table('customers_table')->get();
OR
$customers = Customer::get();
return view('welcome')->with('customers',$customers);
});
You can use$customers in welcome.blade.php as
#foreach($customers as $customer)
{{$customer->name}}
#endforeach

Laravel(500- Internal server error): Unable to get data from model to controller

I have been trying to list a dropdown in the index page with data from database. I created a model and made some changes in controller to display it in my view page but making any change in the controller gives a blank page with 500 Internal server error in the console. Please help me out to sort this problem.
Table name: walker_type
Routes:
Route::get('/', 'WebController#index');
Model: ProviderType.php :
<?php
class ProviderType extends Eloquent {
protected $table = 'walker_type';
}
Controller: WebController.php
public function index() {
$walkerTypeList = ProviderType::all();
return view('website.index')->with(['walkerTypeList' => $walkerTypeList]);
}
View:index.php
#foreach ($walkerTypeList as $car)
<option data-icon="glyphicon-road" value="{{ $car->name }}"> {{ $car->name }} </option>
#endforeach
Had u declare your model below your namespace?
eg. use App\WalkerType;
also you forgot to declare a namespace to your Model.
it should have namespace App;
or if you have a folder for your model to make it more conventional.
you should have a namespace on each of your model.
eg. App\Model
and then use that in every controllers by declarin in between your namespace and class
eg.
namespace App\Controllers;
use App\Model\WalkerType;
class SomeController extends Controller{
protected $data; //this is a class variable that can call anywhere to your class by calling it this way $this->data
public function some_method(){
$this->data['variable_a'] = "some_value"; //this can call in you view later by $variable_a
$this->data['sum'] = 1+4; //result can be display in your view by calling the variable $sum
return view('someview',$this->data);
}
}
I hope this can help you for your project efficiently, cause we had experienced that we forgot to include some of the data that has been processed on the controller and needed to display in your view file but forgot to include.

Resources