Mrenzi's avatar

Laravel model return data or FALSE and fetch messages from controller

Hi guys! I need your help. I created an Account model. Then i created a function there to search and return a list of account

class Account extends Model{
    try{
       $accounts = Account::search($params);

	   ...			

	   if(count(accounts) > 100){
	   		$message = "This is over 100";
	   }else{
	   		$message = "This is under 100";
	   }

	   return $accounts;

	}catch(\Exception $e){
		$message = $e->getMessage();		
		return FALSE;
	}
}

QUESTIONS:

1- I call this function from the SearchController like this Account::search($params); Should functions like this, not referring to a single instance be declared as static or not?

2- The function returns a list of accounts that it finds. But from the controller, if($accounts === FALSE) i need to show the error also if success i need to manage the message. How can i get the message from the Model? What is the best practice?

Thanks in advance M.

0 likes
16 replies
tykus's avatar

@celotrovi I think we're missing some context, can you please format your code correctly by wrapping it within triple backticks

```
// your code
```

Do you call Account::search within Account::search? What is $message used for?

tykus's avatar

@celotrovi that's not valid PHP - you need to wrap this logic with a function. I don't know what error/exception you are thinking here; what might that be? This all should probably be moved up to the Controller (except the actual search implementation, so you can define the $message there

Mrenzi's avatar

@tykus Which one would be? I mean what if you need to return 1 - the result only and not the message 2- also the total number if paginating?

Thanks in advance?

tykus's avatar

@Mrenzi I don't understand what you are asking here. If you are getting a Collection from the model, then get the Collection; why is $message a concern of the Model?

Mrenzi's avatar

@tykus ok lets say you have an exception, does the controller always take care of that or you put the try catch inside the model?

tykus's avatar

@Mrenzi the framework will handle any uncaught exceptions, returning an appropriate response. If you want to catch and handle the exception, you need to do that yourself (in the appropriate context). I don't know or understand what you are trying to achieve, so I can't say what the appropriate context is in this case. Maybe explain what you are trying to achieve rather than how you're trying to achieve it

1 like
Mrenzi's avatar

@tykus Ok, ill explain better. All the things ive been writing are coming from the multiple questions on how to manage things in Laravel. Im new to this framework, and i need to understand things better. The main problem came from this development i was doing. Im creating an application where i need to search on a map accounts living on that range of coordinates and other filters by ajax and i need to call this function from multiple places.

So i created a SearchController

class SearchController extends Controller
{

    public function index(Request $request)
    {
        $pageNum = (isset($request['pageNum']) && $request['pageNum'] > 0) ? (int)$request['pageNum'] : 1;
        $accountTypeConst = (isset($request['search_type']) && in_array($request['search_type'], [1, 2])) ?   $request['search_type'] : NULL; 

        $limit = 10;
        $tmpParams = [
            'accountTypeConst' => $accountTypeConst,
            'tab' => 'list',
            'limit' => $limit,
            'page' => $pageNum,
            'lat' => isset($params['lat']) ? $params['lat'] : 0,
            'lng' => isset($params['lng']) ? $params['lng'] : 0,
            'neLat' => isset($params['neLat']) ? $params['neLat'] : 0,
            'neLng' => isset($params['neLng']) ? $params['neLng'] : 0,
            'swLat' => isset($params['swLat']) ? $params['swLat'] : 0,
            'swLng' => isset($params['swLng']) ? $params['swLng'] : 0,
            'center' => isset($params['center']) ? $params['center'] : '0,0'
        ];


        $items = Account::search($tmpParams);
       

and also i created the search function inside the Account model to return the account items i found after doing some data manipulation.

class Account extends Model
{
    use HasFactory;

 	public function search($params = array())
    {
            $query = Account::with(['brands', 'brandsspecialize', 'country', 'province'])
            ->select(
               
                'accounts.*',
                'services.price AS service_price'
            )
            ->join('countries', 'countries.id', 'accounts.country_id')
            ->join('provinces', 'provinces.id', 'accounts.province_id')
			...

            $accounts = $query->paginate($limit);
  
            $total = $accounts->total();


     
        $items = array();
        foreach ($accounts as $account) :

            $brands = $account->Brands;
            $brand_list = [];

            //dump($brands);
            foreach ($brands as $brand) {
                if ($brand->id == 1) {
                    $brand_list[] = 'Tutti i marchi';
                    break;
                }
                $brand_list[] = $brand->description;
            }

            $brandsSpecialize = $account->BrandsSpecialize;
            $brand_specialize_list = [];
            foreach ($brandsSpecialize as $brand) {
                if ($brand->id == 1) {
                    $brand_specialize_list[] = 'Tutti i marchi';
                    break;
                }
                $brand_specialize_list[] = $brand->description;
            }



            $item = [
                'id' => $account->id,
                'marker_class' => '',
                'img_alt' =>   $account->name,
               .....
               ......
                'is_liked'  => $account->is_favorite, //From query //left join con user_favorite
            ];


            $items[] = $item;


        endforeach;

        return $items;
     }

I also want to return the total. I was thinking putting the total in some variable and fetching that from the controller. But i believe the solution is to return an array of ['items' => $items, 'total' => $total] right?

Mrenzi's avatar

@tykus you can see in the code

$total = $accounts->total();

tykus's avatar

@Mrenzi yeah, that is available in the Paginator instance that you return, why the need for a separate variable???

Mrenzi's avatar

@tykus because in the code i need to make some jobs adding stuff before returning items. Thas why im not returning the paginator.

tykus's avatar

@Mrenzi personally, I’d transform the items in the Paginator instance

Tray2's avatar

You can't write a class like that, classes includes properties and methods, not loose code like you can do in functional programming. I suggest you read up on how OOP works.

Mrenzi's avatar

@Tray2 Is not the model containing the logic of that query? Is not corret to put the business login inside the model?

Tray2's avatar

@Mrenzi Sure, you can place it there. but the code you shared at first wasn't correct.

1 like

Please or to participate in this conversation.