based on the example from here https://scotch.io/tutorials/simple-and-easy-laravel-routing#blog-pages-with-categories-route-parameters
I want to show entries for specific categories.
By calling this Route:
Route::get('menues/{city?}', 'PagesController#menue');
I want to show all entries for a specific city.
This is my Controller:
public function menue($city = null) {
if ($city) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '=', $city)->get();
} else {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '!=', $city)->get();
}
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}
The only thing that doesn't work is, by calling a url with a {city} that doesn't exist in the DB I want to display all entries.
With the code above this doesn't happen. I get a blank page.
How can I fix this? My guess was that the code inside my else statement displays all entries, but this isn't the case.
Do the following:
public function menue($city = null) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}]);
if(if(!is_null($city) && !is_null(City::where('name', $city)->first())) {
$restaurants->where('city', '=', $city);
}
$restaurants = $restaurants->get();
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}
->where('city', '!=', $city) is the problem. If you want to get all articles, remove the condition.
Change the condition to:
if(!is_null($city) && !is_null(City::where('name', $city)->first())
Use Requests $request
public function menue(Request $request) {
if ($request->has('city')) {
I would do something like:
public function menue($city = null) {
if ($city) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '=', $city)->get();
if (restaurants->count() == 0) {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->get();
}
} else {
$restaurants = User::with(['articles' => function ($q){
$q->nowpublished();
}])->where('city', '!=', $city)->get();
}
return view('pages.menues')
->withRestaurants($restaurants)
->withCity($city);
}
Related
I have course search everything works except, when $r->price it's returns all courses not last searched ones. I need to catch last "when" and then filter price by it.
How can i do that?
$courses = Course::when($r->mainCat, function ($query) use ($mainCat) {
$courseIdsArray = Direction::whereIn('course_category_id', $mainCat)->pluck('course_id')->toArray();
return $query->whereIn('id', $courseIdsArray);
})->when($r->level, function ($query, $level) {
return $query->where('level', 'like', "%{$level}%");
})->when($categories && count($categories) > 0, function ($query) use ($categories) {
return $query->whereIn('course_category_id', $categories);
})->when($r->price && in_array($r->price, ['more-expensive', 'less-expensive']), function ($query) use ($r) {
return $query->orderBy('price', $r->price == 'less-expensive' ? 'asc' : 'desc');
}, function ($query) {
return $query->statusOn()->order();
})->paginate(18)->appends($r->query());
what am i doing wrong? pagination isn't working and i'm not getting any error. next button isn't working. is there a solution to this?
class PostsIndex extends Component
public function render()
{
$statuses = Status::all()->pluck('id', 'name');
$schools = School::all();
return view('livewire.posts-index', [
'posts' => Post::with('user', 'school', 'status')
->when($this->status && $this->status !== 'All', function ($query) use ($statuses) {
return $query->where('status_id', $statuses->get($this->status));
})->when($this->school && $this->school !== 'All Schools', function ($query) use ($schools) {
return $query->where('school_id', $schools->pluck('id', 'name')->get($this->school));
})->when($this->filter && $this->filter === 'Top Exp', function ($query) {
return $query->orderByDesc('votes_count');
})->when($this->filter && $this->filter === 'My Exp', function ($query) {
return $query->where('user_id', auth()->id());
})->when($this->filter && $this->filter === 'Spam Posts', function ($query) {
return $query->where('spam_reports', '>', 0)->orderByDesc('spam_reports');
})->when(strlen($this->search) >= 3, function ($query) {
return $query->where('body', 'like', '%'.$this->search.'%');
})
->addSelect(['voted_by_user' => Vote::select('id')
->where('user_id', auth()->id())
->whereColumn('post_id', 'posts.id')
])
->withCount('votes')
->withCount('comments')
->orderBy('id', 'desc')
->simplePaginate(10)
->withQueryString(),
'schools' => $schools,
]);
}
}
i have tried my possible best could not get it to work
Try to add the link {{ $schools->links() }} in the posts-index file
Have a query, how I can filter results by translation relation (by name column)
$item = Cart::select('product_id','quantity')
->with(['product.translation:product_id,name','product.manufacturer:id,name'])
->where($cartWhere)
->get();
my model
Cart.php
public function product($language = null)
{
return $this->hasOne('App\Models\Product','id','product_id');
}
Product.php
public function translations()
{
return $this->hasMany('App\Models\ProductTranslation','product_id','id');
}
Update v1.0
do like this, but query takes too long time
$item = Cart::select('product_id','quantity')
->with(['product.translation', 'product.manufacturer:id,name'])
->where($cartWhere)
->when($search,function ($q) use ($search) {
$q->whereHas('product.translation', function (Builder $query) use ($search) {
$query->where('name', 'like', '%'.$search.'%');
$query->select('name');
});
}
)
->get() ;
Inside the array within your with() method, you can pass a function as a value.
Cart::select('product_id','quantity')
->with([
'product', function($query) {
$query->where($filteringAndConditionsHere);
}
]);
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
i would like to create simple ability for my users to search database table as an optional items, for example search by name or mobile or email. to create this ability i'm created this simple controller:
class SearchTransactionController extends Controller
{
public function search(Request $request)
{
$query = BuyCard::select('*');
foreach ($request->only(['name', 'mobile', 'email']) as $key => $value) {
if (strlen($value) > 0) {
$query->where($key, 'LIKE', "%$value%");
}
}
$query->orderBy('id', 'DESC');
$data = $query->paginate(15);
return view('report_buycard_transactions.index')
->with('info', $data);
}
}
all name,mobile,email is optional for search but my code dont correct search in database and return all columns
it's because adding multiple ->where() calls mean it attempts to find only rows where the search string is in all 3 of those columns, try doing this:
class SearchTransactionController extends Controller
{
public function search(Request $request)
{
$query = BuyCard::select('*');
$first = true;
foreach ($request->only(['name', 'mobile', 'email']) as $key => $value) {
if (strlen($value) > 0) {
if($first){
$query->where($key, 'LIKE', "%$value%");
$first = false;
} else {
$query->orwhere($key, 'LIKE', "%$value%");
}
}
}
$query->orderBy('id', 'DESC');
$data = $query->paginate(15);
return view('report_buycard_transactions.index')
->with('info', $data);
}
}
With the code below, what I wanted was paginate the query I created. But, when I try to add paginate after get, it throws an error. I wanted to remain get since I want to limit to columns that was set on $fields.
What would should be the better idea to paginate this thing? or what's a good substitute for get and limit the columns?
What I tried:
->get($this->fields)->paginate($this->limit)
Part of my controller:
class PhonesController extends BaseController {
protected $limit = 5;
protected $fields = array('Phones.*','manufacturers.name as manufacturer');
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
if (Request::query("str")) {
$phones = Phone::where("model", 'LIKE', '%'. Request::query('str') . '%')
->join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id')
->get($this->fields);
} else {
$phones = Phone::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id')
->get($this->fields);
}
return View::make('phones.index')->with('phones', $phones);
}
}
If you look at the method signature you will see that paginate receives a second argument, $columns. So your solution would be to use
->paginate($this->limit, $this->fields);
Furthermore, you can clean up your controller by changing things slightly:
public function index()
{
$query = Phones::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id');
if ( Request::query('str') ) {
$query->where('model', 'LIKE', '%'. Request::query('str') . '%')
}
$phones = $query->paginate($this->limit, $this->fields);
return view('phones.index')->with('phones', $phones);
}
class Servicios extends CI_Controller
{
public function __construct()
{
parent::__construct();
header('Content-Type: application/json');
if (!$this->lib_validaciones->validarSesion(FALSE))
{
exit(json_encode(array("satisfactorio" => FALSE, "mensaje" => "NO TIENE SESSION ACTIVA")));
}
$this->usuarioId = $this->session->userdata("usuarioId");
}
public function index()
{
exit();
}
public function getPremios()
{
$currentPage = $this->input->get("pag");
\Illuminate\Pagination\Paginator::currentPageResolver(function () use ($currentPage)
{
return $currentPage;
});
$this->load->model('Premio');
$premios = Premio::where('activo', "TRUE")
->with(['Categoria' => function($q)
{
$q->select('id', 'nombre');
}])
->with(['Imagenes' => function ($query)
{
$query->where("activo", "TRUE");
$query->select(["imagenes.id", "imagenes.descripcion",
new Illuminate\Database\Query\Expression(
"CONCAT('" . site_url(PATH_IMAGENES_UPLOAD) . "',imagenes.id,'.',imagenes.extension) as path")
]);
}])
->with(['inventario'])
->withCount(['Favoritos', 'Favoritos AS favorito_usuario' => function ($query)
{
$query->where("usuario_id", $this->usuarioId);
}])
->orderBy("nombre")
->paginate(3);
$premios->setPath(site_url(uri_string()));
$premios->setPageName("pag");
exit(json_encode(array("satisfactorio" => TRUE, "premios" => $premios->toArray())));
}
}